【问题标题】:How can I validate a field based on another field?如何根据另一个字段验证一个字段?
【发布时间】:2016-04-14 08:14:26
【问题描述】:

我正在尝试使用emailemailConfirmationpasswordpasswordConfirmation 等字段的注册表单。验证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 一个简单的验证,那么它会按预期工作。我在这里遗漏了什么吗?

【问题讨论】:

    标签: haskell digestive-functors


    【解决方案1】:

    我在消化函子存储库上获得了帮助。 Thanks cimmanon

    这是最终代码,注意字段名称现在是“password.p1”/“password.p2”,而不仅仅是密码/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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-20
      • 1970-01-01
      • 1970-01-01
      • 2018-09-04
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 2017-02-28
      相关资源
      最近更新 更多