Validation

A validation rule is a plain object in an element's rules: a $type that names a registered rule, the rule's own options and, optionally, a message. Rules are data, so they serialize with the rest of the form, and the engine turns each into a schema that checks the field's value. The engine registers 27 rule types. For a rule of your own, or a check that calls a server, see Custom and async rules.

import { engine } from './engine';

export const signup = engine.defineForm({
	id: 'signup',
	steps: [
		{
			id: 'account',
			title: 'Create your account',
			elements: [
				{
					$type: 'input',
					id: 'email',
					name: 'email',
					label: 'Email',
					inputType: 'email',
					rules: [
						{ $type: 'required', message: 'Email is required' },
						{ $type: 'email', message: 'Enter a valid email address' },
						{ $type: 'maxLength', value: 254, message: 'That address is too long' },
					],
				},
				{
					$type: 'input',
					id: 'username',
					name: 'username',
					label: 'Username',
					rules: [
						{ $type: 'minLength', value: 3 },
						{
							$type: 'pattern',
							value: '^[a-z0-9_]+$',
							message: 'Use lowercase letters, numbers and underscores',
						},
						{
							$type: 'minLength',
							value: 8,
							severity: 'warning',
							message: 'A longer username is easier to find',
						},
					],
				},
			],
		},
	],
});

The property is rules, not validation. Every rule accepts three optional keys besides its own options:

KeyMeaning
messageThe text to show when the rule fails. Without one the issue has no text of its own, and the formatter words it (see below)
idAn identifier for the rule, to tell two rules of one $type apart
severity'error' (default) blocks the submission. 'warning' reports advice that never blocks, with the shape and timing of an error

An empty value passes every rule except required, so email on an optional field accepts a blank. A rule's message is the fallback of the engine's formatter, and a rule without one shows nothing unless the formatter words it: Issue text has the order. Where an issue is stored is in Form state.

Built-in rules

Strings

$typeOptionsHolds when the value
requiredis not empty: a string of spaces counts as present
minLengthvaluehas at least value characters
maxLengthvaluehas at most value characters
patternvalue: a regular expression sourcematches the expression
emailpattern: an expression that replaces the defaultis an email address
urlprotocol, hostname: expressions the URL must matchis a URL
uuidversion: v1 to v5is a UUID, of that version when given
phoneis a phone number
cuidis a CUID
cuid2is a CUID2
ulidis a ULID
hexis a hexadecimal string

Numbers and lists

$typeOptionsHolds when the value
minvalueis at least value
maxvalueis at most value
minItemsvaluehas at least value items
maxItemsvaluehas at most value items

Network and encodings

$typeOptionsHolds when the value
ipv4is an IPv4 address
ipv6is an IPv6 address
cidrversion: v4 or v6is a CIDR range, of that version when given
jwtalg: the algorithm the header must nameis a JSON Web Token
hashalgorithm: md5, sha1, sha256, sha384, sha512 (required)is a hex digest of that algorithm
base64urlSafeis Base64, in the URL-safe alphabet when urlSafe

Dates and times

$typeOptionsHolds when the value
datetimeprecision, offset, localis an ISO 8601 datetime
dateis an ISO 8601 date
timeprecisionis an ISO 8601 time

Rules that read other things

$typeWhat it does
relateCompares the field with other fields: equality, ordering, "at least one of". See Cross-field rules
asyncAsks a server. See Custom and async rules

Cross-field rules

The relate rule compares a field with other fields. Password confirmation, date ordering, "one of these two" and mutual exclusion are the same operation with a different assertion.

import { engine } from './engine';

export const resetPassword = engine.defineForm({
	id: 'reset-password',
	steps: [
		{
			id: 'password',
			title: 'Choose a password',
			elements: [
				{ $type: 'input', id: 'password', name: 'password', label: 'Password', inputType: 'password' },
				{
					$type: 'input',
					id: 'confirm',
					name: 'confirmPassword',
					label: 'Confirm password',
					inputType: 'password',
					rules: [
						{ $type: 'relate', fields: ['password'], assert: 'allEqual', message: 'Passwords must match' },
					],
				},
			],
		},
	],
});

The declaring field's own value comes first in the comparison, then each entry of fields in order.

assertHolds when
allEqualevery value is the same
allDifferentno value repeats
ascendingeach value is greater than or equal to the one before
strictlyAscendingeach value is greater than the one before
descendingeach value is less than or equal to the one before
strictlyDescendingeach value is less than the one before
atLeastOneat least one value is filled
exactlyOneexactly one value is filled
allOrNoneall values are filled, or none are
OptionDefaultDescription
fieldsrequiredReferences to compare against, resolved relative to the declaring field. A dotted reference is absolute from the form root
includeSelftrueWhether the declaring field's value participates, first in the list
as'auto'Comparison basis: string, number, date, boolean or auto
skipWhenIncompletetrueStay quiet while any participating value is empty. Ignored by atLeastOne, exactlyOne and allOrNone, which exist to fire on a partly filled group

Ordering reads left to right with the declaring field first, so "this date must be after that one" is descending. A cross-field rule re-runs when a field it reads changes, not only when its own field is validated, so correcting a password clears the mismatch on the confirmation. The error surfaces once the dependent field has been touched or the form submitted, so typing a password does not light up a confirmation nobody has reached.

Presets

ValidationPresets builds the same rule objects with less typing. Each preset returns a plain rule, so a form authored with presets and one round-tripped through JSON are the same config. The last argument is the optional message.

import { ValidationPresets } from '@schema-engine/forms';

const emailRules = [
	ValidationPresets.string.required('Email is required'),
	ValidationPresets.string.email('Invalid email address'),
	ValidationPresets.string.maxLength(100, 'Email too long'),
];

const confirmRules = [ValidationPresets.relate.matches('password', 'Passwords must match')];
GroupPresets
stringrequired, email, url, uuid, uuidv4, cuid, cuid2, ulid, hex, minLength, maxLength, pattern
numberrequired, min, max
booleanrequired
arrayrequired, minItems, maxItems, nonEmpty (minItems(1))
networkipv4, ipv6
datedatetime, date, time
relatematches (equal), after, before (dates), atLeastOneOf, mutuallyExclusive, allOrNone
customasync(url, options?): the built-in async rule

A preset takes the rule's value first, then the message: minLength(8, 'At least 8 characters'). The relate presets take the field to compare with, or a list of fields, resolved as in Cross-field rules.

Where to go next