Skip to content

Instantly share code, notes, and snippets.

@ayoubkhan558
Created April 26, 2024 03:33
Show Gist options
  • Save ayoubkhan558/1096a52631c8c02b6a329973ac10717a to your computer and use it in GitHub Desktop.
Save ayoubkhan558/1096a52631c8c02b6a329973ac10717a to your computer and use it in GitHub Desktop.
How to validate two fields that depend on each other with Yup
# How to validate two fields that depend on each other with Yup
```js
const schema = yup.object().shape({
propCategory: yup.object().shape({
label: yup.string().required(),
value: yup.string().required(),
icon: yup.string().required(),
}),
propertyType: yup.object().shape({
label: yup.string().required(),
value: yup.string().required()
}),
// Conditionally require fields based on propCategory value
ownerName: yup.string().when("propCategory", {
is: (val) => {
// this will output
console.log(val?.value);
return val?.value === 'Commercial';
},
then: (s) => s.label('Owner Name').required(),
otherwise: (s) => s,
}),
ownerNumber: yup.string().when("propCategory", {
is: (val) => val?.value === 'Commercial',
then: (s) => s.label('Owner Number').required(),
otherwise: (s) => s,
}),
});
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment