Form validation
Validation with rules object
To validate form with rules object, provide an object of functions which take field value as an argument and return error message (any React node) or null if field is valid:
Rule function arguments
Each form rule receives the following arguments:
value
– value of fieldvalues
– all form valuespath
– field path, for exampleuser.email
orcart.0.price
path
argument can be used to get information about field location relative to other fields,
for example you can get index of array element:
Validation based on other form values
You can get all form values as a second rule function argument to perform field validation based on other form values. For example, you can validate that password confirmation is the same as password:
Function based validation
Another approach to handle validation is to provide a function to validate
.
Function takes form values as single argument and should return object that contains
errors of corresponding fields. If field is valid or field validation is not required, you can either return null or simply omit it
from the validation results.
Schema based validation
Out of the box @asuikit/form
supports schema validation with:
You will need to install one of the libraries yourself, as @asuikit/form
package does not depend on any of them.
If you do not know what validation library to choose, we recommend choosing zod
as the most modern and developer-friendly library.
zod
joi
yup
superstruct
Validate fields on change
To validate all fields on change set validateInputOnChange
option to true
:
You can also provide an array of fields paths to validate only those values:
Validate fields on blur
To validate all fields on blur set validateInputOnBlur
option to true
:
You can also provide an array of fields paths to validate only those values:
Clear field error on change
By default, field error is cleared when value changes. To change this, set clearInputErrorOnChange
to false
:
Validation in onSubmit handler
form.onSubmit
accepts two arguments: first argument is handleSubmit
function that will be called with form values, when validation
was completed without errors, second argument is handleErrors
function, it is called with errors object when validation was completed with errors.
You can use handleErrors
function to perform certain actions when user tries to submit form without values,
for example, you can show a notification:
isValid handler
form.isValid
performs form validation with given validation functions, rules object or schema, but unlike
form.validate
it does not set form.errors
and just returns boolean value that indicates whether form is valid.