From 59ded9e2b5f002564945c4e8865a6c21773ee5e7 Mon Sep 17 00:00:00 2001 From: Tad Doxsee Date: Fri, 23 May 2014 11:18:18 -0700 Subject: [PATCH] doubleField may add a zero to some text before sending it to Data.Text.Read so that text such as '.3' may be read as 0.3. --- yesod-form/Yesod/Form/Fields.hs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/yesod-form/Yesod/Form/Fields.hs b/yesod-form/Yesod/Form/Fields.hs index cd678207..c4170f5b 100644 --- a/yesod-form/Yesod/Form/Fields.hs +++ b/yesod-form/Yesod/Form/Fields.hs @@ -80,7 +80,10 @@ import Database.Persist (PersistMonadBackend, PersistEntityBackend) import Text.Blaze.Html.Renderer.String (renderHtml) import qualified Data.ByteString as S import qualified Data.ByteString.Lazy as L -import Data.Text as T (Text, concat, intercalate, unpack, pack, splitOn) +import Data.Text as T ( Text, append, concat, cons, head + , intercalate, isPrefixOf, null, unpack, pack, splitOn + ) +import qualified Data.Text as T (drop, dropWhile) import qualified Data.Text.Read import qualified Data.Map as Map @@ -117,7 +120,7 @@ $newline never doubleField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Double doubleField = Field { fieldParse = parseHelper $ \s -> - case Data.Text.Read.double s of + case Data.Text.Read.double (prependZero s) of Right (a, "") -> Right a _ -> Left $ MsgInvalidNumber s @@ -711,3 +714,19 @@ $newline never incrInts :: Ints -> Ints incrInts (IntSingle i) = IntSingle $ i + 1 incrInts (IntCons i is) = (i + 1) `IntCons` is + + +-- | Adds a '0' to some text so that it may be recognized as a double. +-- The read ftn does not recognize ".3" as 0.3 nor "-.3" as -0.3, so this +-- function changes ".xxx" to "0.xxx" and "-.xxx" to "-0.xxx" + +prependZero :: Text -> Text +prependZero t0 = if T.null t1 + then t1 + else if T.head t1 == '.' + then '0' `T.cons` t1 + else if "-." `T.isPrefixOf` t1 + then "-0." `T.append` (T.drop 2 t1) + else t1 + + where t1 = T.dropWhile ((==) ' ') t0