我有一个Digestive Functors表格,如下所示:
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:没有解析)。
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"
答案 0 :(得分: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"