Validation Guide
React Cool Form supports a wide range of synchronous and asynchronous validation strategies for built-in, form-level, and field-level validation to cover all the cases that you need.
#
Built-in ValidationWe 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. If your validation relies on the related methods, use the pattern attribute or custom validation instead.
#
Form-level ValidationThe validate option provides a convenient way to access the complete values
of the form (a.k.a formState.values), which is useful to validate dependent fields at the same time.
๐ก Please ensure the shape of the
errors
matches the shape of form'svalues
. If you're dealing with complex form data, we've provided a set of utility functions to help you get shit done ๐ฉ.
In addition to write your own logic, it's also possible to use a 3rd-party library such as Yup, Joi, and many others with form-level validation. Let's take a look at the following example:
๐ Looking for the example of Joi? Right here.
#
Field-level ValidationReact Cool Form provides the field method for field-level validation (and data type conversion). Simply register your validator via the ref
prop of a field like the following example:
#
When/How Does Validation Run?By default, React Cool Form runs the above validation methods as follows. You can tell React Cool Form when to run validation by changing the validateOnChange and/or validateOnBlur depends on your needs.
#
When to RunEvent/method | Target | Timing |
---|---|---|
onChange | Individual | Whenever the value of a field has been changed. |
setFieldValue | Individual | Whenever the value of a field has been set. |
setValues | All | Whenever the values of the formState has been set. |
onBlur | Individual | Whenever a field has been touched. If a validation method has been run by the onChange event, it won't be run again. |
onSubmit | All | Whenever a submission attempt is made. |
submit | All | Whenever a submission attempt is made manually. |
validateField | Individual | Manually run field-level validation. |
validateForm | All | Manually run form-level validation. |
#
How to RunWhen validating with mixed ways, the result of each field will be deeply merged according to the following order:
๐ก In order to make the validation results are working correctly via the
individual
target event or method. When using form-level validation, please ensure the shape of theerrors
matches the form'svalues
.
#
Manually Triggering ValidationComing soon...
#
Displaying Error MessagesComing soon...