We support HTML form validation out of the box, a quick and easy way for form validation.
Some validation attributes such as minLength, maxLength, min, and max are designed to validate a field once it has been edited by the user. Therefore when manually triggering these validations, use the pattern attribute or custom validation instead.
The validate option provides a convenient way to access the complete
values of the form (a.k.a formState.values), which is useful to validate by dependent fields during both editing (e.g. onChange, onBlur) and submission phases.
React Cool Form provides the field method for field-level validation. We can also access the form
values with the method to validate by dependent fields during the submission phase. Simply register your validator via the
ref attribute of a field like the following example:
field method can not only be used for validating but also converting data type. When they are used together, just tweak the code as below:
We can manually trigger built-in, field-level, and form-level validation with React Cool Form's
|Individual||Whenever the value of a field has been changed.|
|Individual||Whenever the value of a field has been set.|
|Individual||Whenever a field has been touched. If a validation method has been run by the |
|All||Whenever a submission attempt is made.|
|All||Whenever a submission attempt is made manually.|
|Individual/All||Manually running validation for the field(s) or form.|
When validating with mixed ways, the results are deeply merged according to the following order:
- Built-in validation
- Field-level validation
- Form-level validation
All errors are stored in the formState.errors, we can display error messages by accessing the
errors object via the use method. The method provides an
errorWithTouched option to help us filtering the errors of untouched fields, which is designed based on the Errors in Forms design guideline (No.7). You can enable the feature by setting the option to
true (see related doc).
The built-in validation is turned on by default. Which provides two forms of error reports: the
message (refer to validationMessage) and the
state (refer to ValidityState). You can configure (or disable) it by the builtInValidationMode option.
When the user submits a form that fails the validation, React Cool Form will apply focus to the first field with an error. The focus order is based on the field order (i.e. top-to-bottom and left-to-right), however you can change the order by the focusOnError option.