Created
April 26, 2024 03:33
-
-
Save ayoubkhan558/1096a52631c8c02b6a329973ac10717a to your computer and use it in GitHub Desktop.
How to validate two fields that depend on each other with Yup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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