Validation unstable
Field validation for forms: Foldkit's rules, with each field's state derived from what the user did instead of stored.
make takes the form's fields, each with the Schema of what its control
holds (a string by default), a required message and a list of rules. It
returns a Validation: a State Schema for the Model, functions
that record what the user did, and validate, which derives each field as
NotValidated, Validating, Valid or Invalid.
The Model holds the values as typed, which fields were edited or left, whether a submit was tried, and the server's errors. Errors are never stored, so a rule that reads another field always sees its current value.
Example A sign-up form
import { Validation } from "effect/ui"import { Equal, Redacted, Schema } from "effect"
const Signup = Validation.make({ email: { required: "Email is required", rules: [Validation.Rule.email()] }, password: { value: Schema.Redacted(Schema.String), required: "Password is required", rules: [[(password) => Redacted.value(password).length >= 8, "Must be at least 8 characters"]] }, confirm: { value: Schema.Redacted(Schema.String), required: "Confirm your password", rules: [[(confirm, values) => Equal.equals(confirm, values.password), "Passwords must match"]] }}, { mode: "onChange" })
let state = Signup.init({ email: "", password: Redacted.make(""), confirm: Redacted.make("") })state = Signup.change(state, "password", Redacted.make("hunter22"))state = Signup.change(state, "confirm", Redacted.make("hunter2"))
const { email, confirm } = Signup.validate(state).fieldsemail._tag // => "NotValidated"confirm // => { _tag: "Invalid", value: Redacted.make("hunter2"), empty: false, required: true, errors: ["Passwords must match"] }Constructors
Builds a form's validation from its fields.
When to use
Use when a form's fields show errors as the user fills them in. Put
State in the Model, record each change with change, and derive the
fields with validate in view and update.
Details
validate derives each field in this order:
- Errors from
rejectmake itInvalid, and always show. - An empty value is
Invalidwith therequiredmessage, or acceptable when the field is optional. - The first failing rule is the error, or every failing rule with
errors: "all". - A check that is
Initialor waiting isValidating. A check that returned errors isInvalid. - Otherwise the field is
Valid.
A field shows its result once a submit was tried, or by its mode. A
field that isn't showing, or is optional and empty, is NotValidated.
Gotchas
- Derived errors aren't in the Model or the MessageLog. Read them in a test
with
validate(s.model.form). - A check is typed to never fail. A failed result, from a defect, keeps the
field
Validating: map a fetch that can fail to errors first. - The values are what the controls hold, not a parsed value. Parse them
at submit, with the Schema that
Rule.fromSchemachecks. - The
valueSchemas go in the Model, so history restore writes them intohistory.stateand the server ships them in the page state. Declare a secret such as a password withvalue: Schema.Redacted(Schema.String), and the component's whole state stays out of both: none of its fields restore or hydrate, so keep the form a leaf component. SeeComponent.define. - A form sets
novalidate: native constraint validation isn't used.
Signature
declare function make<S, K extends string>(fields: { [P in string | number | symbol]: FieldOptions<S[P], Values<InferFields<S, K>>> } & { [P in string]: unknown }, options: Options): Validation<InferFields<S, K>>Example A login form with a server error
import { Validation } from "effect/ui"import { Option, Redacted, Schema } from "effect"
const Login = Validation.make({ email: { required: "Email is required", rules: [Validation.Rule.email("Please enter a valid email")] }, password: { value: Schema.Redacted(Schema.String), required: "Password is required" }})
// The default mode shows nothing until a submit is tried.let form = Login.init({ email: "ada@example", password: Redacted.make("") })Login.validate(form).fields.email._tag // => "NotValidated"
form = Login.submit(form)Login.validate(form).fields.email // => { _tag: "Invalid", value: "ada@example", empty: false, required: true, errors: ["Please enter a valid email"] }
form = Login.change(form, "email", "ada@example.com")form = Login.change(form, "password", Redacted.make("secret"))Login.validate(form).value // => Option.some({ email: "ada@example.com", password: Redacted.make("secret") })
// The server's error shows on the password until the password changes.form = Login.reject(form, { password: ["Invalid credentials"] })Login.validate(form).invalid // => trueModels
One rule of a field, as Validation.checklist reports it: its message and whether the field's value meets it.
Gotchas
The message is there for every rule, met or not, so write it as a requirement, such as "At least 8 characters". A message function is called with whatever the field holds, an empty value included.
Signature
interface ChecklistItem { readonly message: string; readonly met: boolean;}Example A password's requirements
import { Validation } from "effect/ui"import { Redacted, Schema } from "effect"
const Signup = Validation.make({ password: { value: Schema.Redacted(Schema.String), required: "Password is required", rules: [ [(password) => Redacted.value(password).length >= 8, "At least 8 characters"], [(password) => /\d/.test(Redacted.value(password)), "At least one number"] ] }})
// Nothing was submitted, so the field shows no error yet. The list is there anyway.const state = Signup.change(Signup.init({ password: Redacted.make("") }), "password", Redacted.make("hunter2"))Signup.checklist(state, "password") // => [{ message: "At least 8 characters", met: false }, { message: "At least one number", met: true }]The errors from async checks, by field: usually a query's result, mapped to a list of errors.
Details
A check is read only when its field is filled in and passes its rules.
While it is Initial or waiting, the field is Validating. A Success
with errors makes it Invalid, and one with none leaves it Valid.
Signature
type Checks<Values> = { [K in keyof Values]: AsyncResult.AsyncResult<ReadonlyArray<string>, never> }A field as Validation.validate derives it.
Details
Each state has the field's value, empty (the field's isEmpty applied
to value) and required, which is true when an empty value would be
an error, for a * next to the label.
Signature
type Field<A> = NotValidated<A> | Validating<A> | Valid<A> | Invalid<A>One field passed to make.
Details
value: the Schema of what the control holds, such asSchema.Booleanfor a checkbox. Defaults toSchema.String.required: the message for an empty value, or a function of every value that returns the message, orfalsewhen the field is optional for those values. Without it an empty value is acceptable and shows asNotValidated.rules: checked in order, only when the value isn't empty.isEmpty: what counts as empty. Defaults to an empty string or array, unwrapping aRedactedfirst.
Signature
interface FieldOptions<S, Values> { readonly isEmpty?: (value: FieldType<S>) => boolean; readonly required?: string | (values: Values) => string | false; readonly rules?: readonly Array<Rule<FieldType<S>, Values>>; readonly value?: S & Top;}The value type of a field: its value Schema's Type, or string when the
field has no value.
Signature
type FieldType<S> = [S] extends [Schema.Top] ? S["Type"] : stringA field with at least one error.
Signature
interface Invalid<A> { readonly _tag: "Invalid"; readonly empty: boolean; readonly errors: readonly [string, string]; readonly required: boolean; readonly value: A;}When a field starts showing its result.
Details
"onChange": once the field was edited."onBlur": once the field was left, recorded withblur."onSubmit": once a submit was tried. The default, as in Base UI.
After a tried submit every field shows its result, in every mode. Errors
from reject always show.
Signature
type Mode = "onChange" | "onBlur" | "onSubmit"A field that isn't showing a result yet, or is optional and empty.
Signature
interface NotValidated<A> { readonly _tag: "NotValidated"; readonly empty: boolean; readonly required: boolean; readonly value: A;}Options for make.
Details
errors: "first", the default, reports the first failing rule.
errors: "all" reports every failing rule, like Foldkit's validateAll.
Signature
interface Options { readonly errors?: "first" | "all"; readonly mode?: Mode;}A rule: a predicate and the message shown when it returns false.
Details
The predicate gets the field's value and every value of the form, so a rule can compare two fields. The rules in Rule ignore the second argument, so they fit any form.
checklist shows the message for every rule, met or not. See
RuleMessage for what that asks of a message function.
Signature
type Rule<A, Values = unknown> = readonly [predicate: (value: A, values: Values) => boolean, message: RuleMessage<A>]A rule's message: a string, or a function of the field's value.
Gotchas
validate calls a message function only with a value that fails the rule.
checklist calls it for every rule, so it also gets a value that meets
the rule, and an empty value, which the predicate never sees. A function
used with checklist must handle an empty value, and return a label that
reads right whether or not the rule is met.
Signature
type RuleMessage<A> = string | (value: A) => stringWhat a form remembers, kept in the Model through Validation.State.
Details
values are what the controls hold. edited and touched list the fields
that were changed and left, submitted records a tried submit, and
rejected holds the server's errors by field. Nothing derived is stored.
Signature
interface State<Values> { readonly edited: readonly Array<Extract<keyof Values, string>>; readonly rejected: { [K in string | number | symbol]: readonly [string, string] }; readonly submitted: boolean; readonly touched: readonly Array<Extract<keyof Values, string>>; readonly values: Values;}A field that passes its rules and its check.
Signature
interface Valid<A> { readonly _tag: "Valid"; readonly empty: boolean; readonly required: boolean; readonly value: A;}What Validation.validate derives from a State.
Details
fields: each field as a Field.value:Someof the values when every field is acceptable, whether or not it shows yet. Use it to gate a submit.invalid: some field isInvalid.validating: some field isValidating.
Signature
interface Validated<Values> { readonly fields: { [K in string | number | symbol]: Field<Values[K]> }; readonly invalid: boolean; readonly validating: boolean; readonly value: Option<Values>;}A field that passes its rules and waits on a check.
Signature
interface Validating<A> { readonly _tag: "Validating"; readonly empty: boolean; readonly required: boolean; readonly value: A;}A form's validation, made by make.
Details
State goes in the Model. init, change, blur, submit and
reject record what the user and the server did, and return a new state.
change, blur and reject are also data-last, so they fit an updater:
{ ...model, form: Form.change("email", value)(model.form) }.
change(state, name, value): sets the value, marks the field edited and drops its server errors.blur(state, name): marks the field touched.submit(state): records a tried submit, so every field shows its result.reject(state, { name: errors }): stores server errors. They show at once and hold backvalueuntil the field changes. An empty list clears a field's errors.passes(state, name): whether the field is filled in and passes its own rules, ignoring checks and server errors. Use it to enable the query behind a check.checklist(state, name): every rule of the field with its message and whether the value meets it, in the order written. It ignores the mode,errors, checks and server errors, so a list of requirements can show from the first render. An empty value meets no rule. Each rule's message function is called every time, with an empty value too.validate(state, checks?): derives a Validated. It is pure, so call it fromview,updateand tests.
Signature
interface Validation<Fields extends Validation.Fields> { readonly blur: { (name: Extract<keyof Fields>): (self: State<Values<Fields>>) => State<Values<Fields>>; (self: State<Values<Fields>>, name: Extract<keyof Fields>): State<Values<Fields>>; }; readonly change: { <K extends string>(name: K, value: Values<Fields>[K]): (self: State<Values<Fields>>) => State<Values<Fields>>; <K extends string>(self: State<Values<Fields>>, name: K, value: Values<Fields>[K]): State<Values<Fields>>; }; readonly checklist: (self: State<Values<Fields>>, name: Extract<keyof Fields>) => readonly Array<ChecklistItem>; readonly init: (values: Validation.Values<Fields>) => State<Values<Fields>>; readonly passes: (self: State<Values<Fields>>, name: Extract<keyof Fields>) => boolean; readonly reject: { (errors: { [K in string]: readonly Array<string> }): (self: State<Values<Fields>>) => State<Values<Fields>>; (self: State<Values<Fields>>, errors: { [K in string]: readonly Array<string> }): State<Values<Fields>>; }; readonly State: Codec<State<Values<Fields>>, State<Encoded<Fields>>, Fields[keyof Fields]["DecodingServices"], Fields[keyof Fields]["EncodingServices"]>; readonly submit: (self: State<Values<Fields>>) => State<Values<Fields>>; readonly validate: (self: State<Values<Fields>>, checks?: Checks<Values<Fields>>) => Validated<Values<Fields>>;}Other
Validation
unstableTypes that make up a Validation.
Rules
Foldkit's rules, with its patterns and default messages.
Details
Each rule takes an optional message, a string or a function of the value,
that replaces the default. A rule's predicate never sees an empty value: an
empty field is checked against required instead. A message function can
see one, because checklist calls it for every rule. See
RuleMessage.
minLength(min),maxLength(max): the string's length.pattern(regex): the string matchesregex.email(): something,@, something,., something, with no spaces.url({ requireProtocol }): starts withhttp://orhttps://, or withrequireProtocol: falsea bare domain such asexample.com.startsWith(prefix),endsWith(suffix),includes(substring).equals(expected),oneOf(values): the string is one of these.minItems(min),maxItems(max): the array's length.fromSchema(schema, message): the value decodes throughschema. Use it to keep a rule and the parser you run at submit the same Schema.
Signature
declare const Rule: { readonly email: (message: RuleMessage<string>) => Rule<string>; readonly endsWith: (suffix: string, message?: RuleMessage<string>) => Rule<string>; readonly equals: (expected: string, message?: RuleMessage<string>) => Rule<string>; readonly fromSchema: <A, I>(schema: Codec<A, I>, message: RuleMessage<I>) => Rule<I>; readonly includes: (substring: string, message?: RuleMessage<string>) => Rule<string>; readonly maxItems: (max: number, message?: RuleMessage<readonly Array<unknown>>) => Rule<readonly Array<unknown>>; readonly maxLength: (max: number, message?: RuleMessage<string>) => Rule<string>; readonly minItems: (min: number, message?: RuleMessage<readonly Array<unknown>>) => Rule<readonly Array<unknown>>; readonly minLength: (min: number, message?: RuleMessage<string>) => Rule<string>; readonly oneOf: (values: readonly Array<string>, message?: RuleMessage<string>) => Rule<string>; pattern: (regex: RegExp, message: RuleMessage<string>) => Rule<string>; readonly startsWith: (prefix: string, message?: RuleMessage<string>) => Rule<string>; readonly url: (options: { readonly message?: RuleMessage<string>; readonly requireProtocol?: boolean; }) => Rule<string>;}Example Rules with default and custom messages
import { Validation } from "effect/ui"import { Schema } from "effect"
const Rule = Validation.Rule
const Profile = Validation.make({ name: { required: "Name is required", rules: [Rule.minLength(2)] }, website: { rules: [Rule.url({ requireProtocol: false })] }, age: { rules: [Rule.fromSchema(Schema.FiniteFromString, (age) => age + " is not a number")] }}, { mode: "onChange", errors: "all" })
const state = Profile.change(Profile.init({ name: "", website: "", age: "" }), "age", "ten")Profile.validate(state).fields.age // => { _tag: "Invalid", value: "ten", empty: false, required: false, errors: ["ten is not a number"] }