3

我正在尝试有一个注册表单,其中包含emailand emailConfirmation, orpassword和等字段passwordConfirmation。验证emailpassword容易,有规则,我已经编写了相应的函数。

其他两个虽然更难。我发现了这个问题并尝试像这样编写我的代码:

表单定义,使用 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进行简单验证,那么它会按预期工作。我在这里错过了什么吗?

4

1 回答 1

1

我在消化功能存储库上得到了帮助。谢谢西玛侬

这是最终代码,注意字段名称现在是“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"
于 2016-04-21T18:41:56.700 回答