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

时间:2016-12-26 14:11:46

标签: elm

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

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

每当您看到展示andThensucceedfail函数的软件包时,这都表明您可以分开"剥离"检查并将其值与另一个函数绑定的值。在这种情况下,我们可以使用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))
        ...

答案 1 :(得分:0)

解决方案接近Chad提供的解决方案,基于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)
                )
        )