VA Forms Library - How to validate a field based on values from another field
When working with forms, we might come across a scenario where we need to validate one field based on the value of another field. You can add ui:validation
on any field or object in uiSchema
, which allows you to validate groups of fields together.
Let us understand with the following form config example:
page1: {
path: 'first-page',
title: 'First Page',
uiSchema: {
email: {
'ui:title': 'Email',
},
confirmEmail: {
'ui:title': 'Confirm email'
},
'ui:validations': [
(errors, field) => {
if (field.email !== field.confirmEmail) {
errors.confirmEmail.addError('Sorry, your emails must match');
}
}
]
},
schema: {
type: 'object',
properties: {
email: {
type: 'string'
},
confirmEmail: {
type: 'string'
}
}
}
}
Since we moved the validation array up to the root of uiSchema
, the field data is passed in an object containing both email
and confirmEmail
, and we can set validation errors on either field.
Example
See the VRE Form 28-8832 for a code example that contains email
and confirmEmail
validation.
Help and feedback
Get help from the Platform Support Team in Slack.
Submit a feature idea to the Platform.