我正在使用 Elm Form https://github.com/etaque/elm-form ,但我无法弄清楚两个字段的验证,我想验证密码和密码确认字段是否匹配。
这是我到目前为止所拥有的:
validate : Validation String RegUser
validate =
map6 RegUser
(field "email" email)
(field "password" (string |> andThen nonEmpty))
(field "passwordConfirmation" (string |> andThen nonEmpty))
(field "firstName" (string |> defaultValue ""))
(field "lastName" (string |> defaultValue ""))
(field "companyName" (string |> defaultValue ""))
完整代码:https://github.com/werner/madison-elm/blob/master/src/elm/Components/Register/Models.elm
感谢您的帮助。
最佳答案
每当您看到公开 andThen
、succeed
和 fail
函数的包时,这都是一个很好的迹象,表明您可以“剥离”要检查其值并将其值与另一个函数绑定(bind)的值。在这种情况下,我们可以使用 andThen
两次来构建一个验证函数,该函数会查看两个命名字段并检查它们是否匹配:
matchingFields : String -> String -> Validation String String
matchingFields masterField confirmField =
field masterField string
|> andThen (\masterVal -> field confirmField string
|> andThen (\confirmVal ->
if masterVal == confirmVal then
succeed masterVal
else
fail (customError "Values do not match")))
然后您可以在整体验证函数中使用它,如下所示:
validate : Validation String RegUser
validate =
map6 RegUser
(field "email" email)
(matchingFields "password" "passwordConfirmation" |> andThen nonEmpty)
(field "passwordConfirmation" (string |> andThen nonEmpty))
...
关于elm - 验证 Elm 和 Elm-Form 中的两个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41332485/