Created
January 15, 2016 12:39
-
-
Save shelakel/9af3f87fcc31a694194a to your computer and use it in GitHub Desktop.
Elm Validation module first try
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module Validation | |
| ( InputState(Initial, HasError, OK) | |
| , InputValue | |
| , inputValue, getInputValue, setInputValue | |
| , hasError, getError | |
| , required, email, checked | |
| , rules | |
| ) where | |
| import List exposing(foldl) | |
| import Regex exposing(regex, contains) | |
| -- todo: async validation functions | |
| type InputState = Initial | HasError String | OK | |
| type alias InputValue value' = (value', InputState) | |
| inputValue : value' -> InputValue value' | |
| inputValue value' = (value', Initial) | |
| getInputValue : InputValue input' -> input' | |
| getInputValue input' = (fst input') | |
| setInputValue : model' -> value' -> (model' -> value' -> InputState) -> InputValue value' | |
| setInputValue model' value' validate = (value', validate model' value') | |
| hasError : InputValue input' -> Bool | |
| hasError input' = case (snd input') of | |
| HasError _ -> True | |
| _ -> False | |
| getError : InputValue input' -> String | |
| getError input' = | |
| case (snd input') of | |
| HasError err -> err | |
| _ -> "" | |
| -- validations | |
| required : String -> model' -> String -> InputState | |
| required errorMessage' model' value' = if value' == "" then HasError errorMessage' else OK | |
| email : String -> model' -> String -> InputState | |
| email errorMessage' model' value' = | |
| if value' == "" | |
| then OK | |
| else if not <| contains ( regex ( | |
| "^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9]" | |
| ++ "(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:.[a-zA-Z0-9]" | |
| ++ "(?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") ) value' | |
| then HasError errorMessage' | |
| else OK | |
| checked : String -> model' -> Bool -> InputState | |
| checked errorMessage' model' value' = if value' then OK else HasError errorMessage' | |
| rules : List (model' -> value' -> InputState) -> (model' -> value' -> InputState) | |
| rules rules' = (\model' value' -> foldl | |
| (\rule' state' -> | |
| case state' of | |
| HasError _ -> state' | |
| _ -> rule' model' value' ) | |
| OK rules' ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment