gpt4 book ai didi

haskell - 如何根据另一个字段验证一个字段?

转载 作者:行者123 更新时间:2023-12-04 18:00:10 25 4
gpt4 key购买 nike

我正在尝试创建一个注册表单,其中包含 emailemailConfirmation,或者 passwordpasswordConfirmation。验证 emailpassword 很容易,有规则而且我已经编写了相应的函数。

另外两个更难。我找到了这个 question并尝试像这样编写我的代码:

表单定义,使用 Blaze:

registrationForm :: (View Html) -> Html
registrationForm view = docTypeHtml $ do
form ! name "registration" ! method "post" ! action "/register" $ do
fieldset $ do
label ! for "password" $ (text "Password")
inputText "password" view
errorList "password" view

br

label ! for "passwordConfirmation" $ (text "Password Confirmation")
inputText "passwordConfirmation" view
errorList "passwordConfirmation" view

和验证器:

data Password = Password { password :: Text }

validateForm :: Monad m => Form Html m Password
validateForm =
Password
<$> "password" .: validatePassword
where
validatePassword =
validate fst' $ (,) <$> ("password" .: D.text Nothing)
<*> ("passwordConfirmation" .: D.text Nothing)
fst' (p1, p2) | p1 == p2 = Success p1
| otherwise = Error "Passwords must match"

但是每当我运行服务器时,我都会收到一条消息说“密码不是一个字段”。如果我删除验证并给 password 一个简单的验证,那么它会按预期工作。我在这里遗漏了什么吗?

最佳答案

我在 digestive-functors 库上得到了帮助。 Thanks cimmanon

这是最终代码,注意字段名称现在是“password.p1”/“password.p2”,而不仅仅是 password/passwordConfirmation。

registrationForm :: (View Html) -> Html
registrationForm view = docTypeHtml $ do
form ! name "registration" ! method "post" ! action "/register" $ do
fieldset $ do
inputText "password.p1" view
br
inputText "password.p2" view
errorList "password" view
data Password = Password { password :: Text }

验证器是一样的,除了新的名字:

validateForm :: Monad m => Form Html m Password
validateForm =
Password
<$> "password" .: validatePassword
where
validatePassword =
validate fst' $ (,) <$> ("p1" .: D.text Nothing)
<*> ("p2" .: D.text Nothing)
fst' (p1, p2) | p1 == p2 = Success p1
| otherwise = Error "Passwords must match"

关于haskell - 如何根据另一个字段验证一个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36617296/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com