module Validated exposing (Validated(..)
, valid
, orDefault
, encode
, Validator
, and
, notEmpty
, format
, maxLength
, registrationNumber
, postcode)
import Json.Encode as Json
import Regex
import String
type Validated value error = Clean | Valid value | Invalid value error
valid : Validated value error -> Bool
valid validated =
case validated of
Valid _ -> True
_ -> False
orDefault : Validated value error -> value -> value
orDefault validated default =
case validated of
Valid x -> x
_ -> default
encode : (value -> Json.Value) -> Validated value error -> Json.Value
encode encoder validated =
case validated of
Valid x -> encoder x
_ -> Json.null
type alias Validator value error = (value -> Validated value error)
and : Validator value error -> Validator value error -> Validator value error
and a b value =
case a value of
Clean -> Clean
Valid _ -> b value
Invalid x y -> Invalid x y
notEmpty : Validator String String
notEmpty value =
if value == "" then
Invalid value "required"
else
Valid value
format : String -> Validator String String
format format value =
if Regex.contains (Regex.regex format) value then
Valid value
else
Invalid value "invalid format"
maxLength : Int -> Validator String String
maxLength length value =
if String.length value <= length then
Valid value
else
Invalid value ("max length: " ++ (toString length))
registrationNumber : Validator String String
registrationNumber = format "^\\d{8}$"
postcode : Validator String String
postcode = format "^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$"