1

我有一个消化函子形式,如下所示:

dateTimeForm :: Monad m => Maybe LocalTime -> Form Text m LocalTime
dateTimeForm t = LocalTime
    <$> "date" .: stringRead "Must be a valid date" (localDay <$> t)
    <*> "time" .: stringRead "Must be a valid time" (localTimeOfDay <$> t)

我用于此表单的输入元素是<input type="date" /><input type="time" />。这对于此表单的日期部分非常有效,但在时间部分则效果不佳。支持时间输入元素的浏览器只提交小时和分钟(例如“18:00”),但 TimeOfDay 需要小时、分钟秒。这会导致 stringRead 失败,并且 Digestive Functors 向用户报告错误(“必须是有效时间”)。

我尝试像这样解决这个问题,但如果用户提交的时间无效,他们将不再从 Digestive Functors 获得有吸引力的错误(Prelude.read: no parse)。

dateTimeForm :: Monad m => Maybe LocalTime -> Form Text m LocalTime
dateTimeForm t = toLocalTime
    <$> "date" .: stringRead "Must be a valid date" (localDay <$> t)
    <*> "time" .: string (show . localTimeOfDay <$> t)
    where
        toLocalTime d x = LocalTime d $ read $ if length x == 8 then x else x <> ":00"
4

1 回答 1

2

我想我正在寻找的是validate功能和一点帮助maybeRead。这似乎有效:

dateTimeForm :: Monad m => Maybe LocalTime -> Form Text m LocalTime
dateTimeForm t = LocalTime
    <$> "date" .: stringRead "Must be a valid date" (localDay <$> t)
    <*> "time" .: validate validTime (string (show . localTimeOfDay <$> t))
    where
        -- the time input element only submits hours and minutes ("18:00"), which is 5 characters long
        validTime x = case maybeRead (if length x == 5 then x <> ":00" else x) of
            Just x' -> Success x'
            _ -> Error "Must be a valid time"
于 2013-10-18T19:25:50.467 回答