Simple tools for validation. See also Richard Feldman's elm-validate.
Maybe a -> Result e b
A validator is a function that takes a possibly-invalid form, and
either returns an error message, or a form that is definitely valid. For example:
type alias Form =
{ message : Maybe String
, email : Maybe String
, firstName : Maybe String
, age : Maybe Int
}
type alias ValidForm =
{ message : String
, email : String
, firstName : String
, age : Int
}
validateForm : Form -> Result String ValidForm
validateForm form =
Ok ValidForm
|: notBlank "Message is required and may not be blank." form.message
|: email "Email is required and may not be blank." form.email
|: matches (caseInsensitive (regex "^[a-z]+$")) "First name may only contain letters." form.firstName
|: required "Age is required" form.age
An error message is typically a String
, but may be any type you choose.
apply : Result e a -> Result e (a -> b) -> Result e b
Chain validators together. (Hat tip to CircuitHub, who inspired the syntax and guided the code with their elm-json-extra library.)
required : e -> Validator e a a
A field that might be Nothing
, but is only valid if it is Just a
.
notBlank : e -> Maybe String -> Result e String
A field that might be Nothing
, but is only valid if it is a non-empty String
.
matches : Regex -> e -> Maybe String -> Result e String
A field that must match the given regex.
email : e -> Validator e String String
This email regex updated with the one found in rtfeldman/elm-validate
.
It is much more comprehensive than the previous version found here, but
remember that the only real way to validate an email address is to
send something to it and get a reply.
emailRegex : Regex