Changeset
Validation
Accumulating, field-keyed validation for forms and API bodies.
You build a record with succeed and apply, tag each Result with field, and read failures as a Dict String (List String). Errors from every field merge instead of stopping at the first one, so a form can show all problems at once.
import Changeset
import Changeset.Validate as Validate
type alias Form =
{ title : String
, body : String
}
validate : String -> String -> Changeset.Changeset Form
validate title body =
Changeset.succeed (\t -> \b -> { title = t, body = b })
|> Changeset.apply
(Changeset.field "title"
(Validate.all [ Validate.trimNonEmpty, Validate.minLength 3 ] title)
)
|> Changeset.apply
(Changeset.field "body" (Validate.trimNonEmpty body))Branch with withChangeset, or call errorsOn / errorMessages for the view. Predicates live in [Changeset.Validate]. A full registration form is in `examples/04_conduit` (`Page.Register`).
Types
Changeset
type Changeset ok = Changeset { errors : Dict String (List String)
, ok : Maybe ok
}A validation that may carry a value and zero or more field errors.
Errors accumulate across apply / andThen. ok may still be present after addError; isValid and toResult consult the error dict.
Examples
Changeset.succeed "ok" : Changeset StringError
type alias Error =
{ field : String
, message : String
}One field error as a flat record (useful when encoding or logging).
Examples
{ field = "email", message = "can't be blank" }Values
succeed
succeed : a -> Changeset aStart a pipeline with the constructor for your validated record.
Examples
Changeset.succeed (\title -> \body -> { title = title, body = body })fail
fail : String -> Changeset aA failed changeset with a single base (empty-field) error.
Use this for whole-form failures that are not tied to one input, such as "email already taken" from the server.
Examples
Changeset.fail "email already taken"field
field : String -> Result String a -> Changeset aTag a Result with a field name for the error dict.
Examples
Changeset.field "email" (Validate.trimNonEmpty rawEmail)Pipe [Changeset.Validate] helpers (or your own `String -> Result String a`) into the second argument.
optional
optional : String -> String -> (String -> Result String a) -> Changeset (Maybe a)Optional text field: blank (after trim) becomes Nothing; otherwise parse and wrap in Just.
Examples
Changeset.optional "bio" rawBio Validate.trimNonEmpty
-- "" -> Ok Nothing (no error)
-- " hi " -> Ok (Just "hi") after a successful parsemap
map : (a -> b) -> Changeset a -> Changeset bTransform the successful value. Errors are unchanged.
Examples
Changeset.field "age" (String.toInt raw)
|> Changeset.map (\n -> n + 1)apply
apply : Changeset a -> Changeset (a -> b) -> Changeset bPipe the next field into a succeed pipeline. Errors from both sides merge; ok stays only when both sides have a value.
Examples
Changeset.succeed (\u -> \e -> { username = u, email = e })
|> Changeset.apply (Changeset.field "username" (Validate.trimNonEmpty username))
|> Changeset.apply (Changeset.field "email" (Validate.trimNonEmpty email))andThen
andThen : (a -> Changeset b) -> Changeset a -> Changeset bChain a second changeset when the first has a value. Errors from both are merged. The callback still runs when the first already has errors (Ecto-style), so later fields can contribute more messages.
Examples
Changeset.field "password" (Validate.minLength 8 raw)
|> Changeset.andThen
(\password ->
Changeset.field "confirm"
(if confirm == password then
Ok password
else
Err "does not match"
)
)mapError
mapError : (String -> String) -> Changeset a -> Changeset aRewrite every error message.
Examples
Changeset.fail "blank"
|> Changeset.mapError (\msg -> "Title " ++ msg)fromResult
fromResult : Result String a -> Changeset aUntagged Result (errors land under the empty field name "").
Examples
Changeset.fromResult (String.toInt "42")fromMaybe
fromMaybe : String -> Maybe a -> Changeset aJust becomes succeed; Nothing becomes fail message.
Examples
Changeset.fromMaybe "not found" (Dict.get id users)addError
addError : String -> String -> Changeset a -> Changeset aAttach a field error without clearing a present ok.
Useful after a successful parse when a uniqueness check fails later.
Examples
changeset
|> Changeset.addError "email" "already taken"errors
errors : Changeset a -> Dict String (List String)All field errors as a dict.
Examples
Changeset.errors changeset
-- Dict.fromList [ ("email", [ "can't be blank" ]) ]errorsOn
errorsOn : String -> Changeset a -> List StringMessages for one field (empty list when none). Wire this into the view next to that input.
Examples
Changeset.errorsOn "email" changeseterrorMessages
errorMessages : Changeset a -> List StringFlat list of every message (field key order). Handy for a summary banner above the form.
Examples
Changeset.errorMessages changesetisValid
isValid : Changeset a -> BoolTrue when there are no errors.
Examples
Changeset.isValid changesettoResult
toResult : Changeset a -> Result (Dict String (List String)) aOk only when valid and a value is present.
Examples
case Changeset.toResult changeset of
Ok form ->
submit form
Err _ ->
showErrors changesetwithChangeset
withChangeset : { onSuccess : a -> b , onFailure : Dict String (List String) -> b } -> Changeset a -> bBranch on success vs the error dict (submit vs show field errors).
Examples
Changeset.withChangeset
{ onSuccess = \form -> submit form
, onFailure =
\_ ->
{ model
| summary = Changeset.errorMessages changeset
, titleErrors = Changeset.errorsOn "title" changeset
}
}
changeset