验证 Elm 和 Elm-Form 中的两个字段

Validates two fields in Elm and Elm-Form

我正在使用 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

感谢您的帮助。

任何时候您看到公开 andThensucceedfail 函数的包,这都很好地表明您可以 "peel apart" 检查和绑定的值它的价值与另一个功能。在这种情况下,我们可以使用 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))
        ...

基于https://github.com/etaque/elm-form/issues/75#issuecomment-269861043:

,该解决方案接近乍得提供的解决方案
validate : Validation TranslationId RegUser
validate =
    map6 RegUser
        (field "email" email)
        (field "password" (string |> andThen nonEmpty))
        ((field "password" string) |> andThen validateConfirmation)
        (field "firstName" (string |> defaultValue ""))
        (field "lastName" (string |> defaultValue ""))
        (field "companyName" (string |> defaultValue ""))

validateConfirmation : String -> Validation TranslationId String
validateConfirmation password =
    field "passwordConfirmation"
        (string
            |> andThen
                (\confirmation ->
                    if password == confirmation then
                        succeed confirmation
                    else
                        fail (customError PasswordNotMatch)
                )
        )