简体   繁体   English

在将表单提交数据发送到stringRead之前修改它

[英]Modifying form submission data before it gets sent to stringRead

I have a Digestive Functors form that looks like this: 我有一个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)

The input elements I'm using for this form are <input type="date" /> and <input type="time" /> . 我用于此表单的输入元素是<input type="date" /><input type="time" /> This works very well for the date portion of this form, but not so well on the time portion. 这适用于此表单的日期部分,但在时间部分不太好。 Browsers that support the time input element only submit the hours and minutes (eg. "18:00"), but a TimeOfDay requires hours, minutes, and seconds. 支持时间输入元素的浏览器仅提交小时和分钟(例如“18:00”),但TimeOfDay需要小时,分钟秒。 This causes stringRead to fail and Digestive Functors reports an error to the user ("Must be a valid time"). 这会导致stringRead失败并且Digestive Functors向用户报告错误(“必须是有效时间”)。

I tried working around this like so, but if the user submits an invalid time, they no longer get an attractive error from Digestive Functors (Prelude.read: no parse). 我尝试解决这个问题,但如果用户提交的时间无效,他们就不会再从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"

I guess what I was looking for is the validate function and a little help from maybeRead . 我想我要找的是validate功能和maybeRead的一些帮助。 This appears to work: 这似乎有效:

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM