Validation
Learn how to manage synchronous and asynchronous validation.
Crustack form uses field-level validation instead of form-level schemas. This approach prevents duplicating validation logic and keeps validation rules close to their respective fields.
Field-level validation simplifies complex scenarios like multi-step forms and conditional fields by only validating mounted fields. This makes the form more maintainable and performant.
Can I use a validation library?
Yes, you can use any validation library that is compliant with the Standard Schema Specification.
When is validation performed?
Validation occurs:
- whenever form values change
- when a submit attempt is made
- when onSubmit resolves/rejects
This ensures that dependent fields are updated based on the new values, maintaining form consistency.
When is the error message displayed?
Error messages appear when a field is touched and the validate function returns an error string. A field becomes touched either through the setFieldTouched function or when submitting the form.
Sync Validation
Basic validation
Simple field validation:
Dependent fields
Validate a field based on the value of another field:
Field Arrays
Validation can also be applied to field arrays to have one error message for all fields in the array.
Async Validation
Submission based async validation
Validate fields based on the submission state.
Field-level async validation
Check if an email is already used before subscribing.