validate takes one rule per field. A rule is a function that gets the field value, all the values and the path, and returns the error message or null.
Rules run when the user submits the form or when you call validate().
Write your own rule or use the validators that come ready. The second argument gives access to the other fields.
const form = useForm({
initialValues: { password: '', confirm: '' },
validate: {
password: hasLength({ min: 8 }, 'Use at least 8 characters'),
confirm: (value, values) =>
value === values.password ? null : 'The passwords do not match'
}
})
validate also accepts a function that gets the values and returns all the errors at once. Use it when the rules depend on each other.
const form = useForm({
initialValues: { start: 1, end: 1 },
validate: (values) =>
values.end < values.start ? { end: 'End must come after start' } : {}
})
By default a field is checked on submit, and its error clears as soon as the user changes it. Set clearInputErrorOnChange to false to keep the error until the next check.
Set validateInputOnChange or validateInputOnBlur to true to check every field while the user fills the form, or to a list of paths to check only those.
The email is checked on change and the name on blur.
onBlur only fires on fields that have it, such as Input and Textarea. The other fields count as touched when their value changes.
validate() checks every field and returns { hasErrors, errors }. validateField(path) checks one field and returns whether it is valid.
Use them for steps of a longer form, where each step checks only its own fields.
| Name | Description | Type |
|---|---|---|
| validate | rules by field path, or one function that returns the errors | Record<string, rule> | (values) => Record<string, string> |
| validateInputOnChange | check every field, or only the listed paths, on change | boolean | string[] |
| validateInputOnBlur | check every field, or only the listed paths, on blur | boolean | string[] |
| clearInputErrorOnChange | clear the error of a field when it changes, true by default | boolean |
type FormRule = (
value: unknown,
values: unknown,
path: string
) => string | null | undefined