2016-12-26 15 views
1

我使用Elm表https://github.com/etaque/elm-form,但我無法弄清楚兩個字段的驗證,我想驗證密碼和密碼確認字段是否匹配。驗證Elm和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

感謝您的幫助。

回答

0

的解決方案是接近於由乍得提供的一個,基於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) 
       ) 
     ) 
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)) 
     ...