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

标签 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

感谢您的帮助。

最佳答案

每当您看到公开 andThensucceedfail 函数的包时,这都是一个很好的迹象,表明您可以“剥离”要检查其值并将其值与另一个函数绑定(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/

相关文章:

arrays - ELM 如何解码 json 数组中的不同值

Elm 联合子集

markdown - 如何在Elm中使用Markdown : is it [markdown| or [markdown |?

css - 努力将 CSS 样式应用到 Elm 应用程序

elm - 如何将项目添加到多行选择并在 View 中显示它们

types - 理解这个 elm url-parser Parser 类型声明

Elm 组件和 View : When we should use `Html msg` and when `Html Msg`

list - 元素在列表中的位置

javascript - Redux - 让不可能的状态成为可能