Forms and validation
A changeset collects field errors so you can show every problem at once: on an HTML form, or as a 422 JSON body. Predicates live in Changeset.Validate; the accumulator is Changeset.
The idea
You start with Changeset.succeed and a constructor for the record you want. Each input becomes a Changeset.field wrapping a Result. Changeset.apply merges them: all errors accumulate, and you only get an Ok value when every field succeeded.
That is the same shape as Elm's Json.Decode.mapN, but keyed by field name so the view can place messages next to inputs.
Validate, then branch
Pipe [Changeset.Validate] helpers (or your own parsers) into `field`. Compose several rules with `Validate.all` (first failure wins for that field).
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))On submit, branch with withChangeset. On failure, keep the raw inputs in the model and fill errorsOn / errorMessages for the view. On success, fire the HTTP request or database write.
Changeset.withChangeset
{ onSuccess = \form -> submit form
, onFailure =
\_ ->
{ model
| summary = Changeset.errorMessages changeset
, titleErrors = Changeset.errorsOn "title" changeset
}
}
changesetOptional fields
Changeset.optional treats blank (after trim) as Nothing with no error. Non-blank values run your parse function and wrap a success in Just.
Changeset.optional "bio" rawBio Validate.trimNonEmptyWhere to go next
API details: [Changeset] and [Changeset.Validate] in the stdlib. A full registration form (domain wrappers plus per-field UI errors) is in `examples/04_conduit` (`Page.Register`).