krisajenkins/elm-exts/20.0.0

NOTE: this package is not compatible with Elm 0.19.1

Exts.Validation

Simple tools for validation. See also Richard Feldman's elm-validate

type alias Validator e a =
Maybe a -> Result e a

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 =
  { email : Maybe String
  , age : Maybe Int
  }


type alias ValidForm =
  { email : 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 -> b) -> Result e a -> Result e b

Chain valiadators together.

(Hat tip to CircuitHub, who inspired the syntax and guided the code with their elm-json-extra library.)

(|:) : Result e (a -> b) -> Result e a -> Result e b

Convenient synonym for apply.

required : e -> Validator e a

A field that might be Nothing, but is only valid if it is Just a.

notBlank : e -> Validator e String

A field that might be Nothing, but is only valid if it is a non-empty String.

matches : Regex -> e -> Validator e String

A field that must match the given regex.

email : e -> Validator e String

A basic email regex. This is incredibly simplistic, but is included for convenience.

Remember that the only real way to validate an email address is to send something to it and get a reply.

emailRegex : Regex