I would like to know how do I validate a field only when it exists.
My problem is that I have a phone field, but this field is dynamic and may or may not exist in the DOM, and I would like to validate it in my schema when it exists, but the problem is that when I put phone: Yup.string ().Required(), these fields are stuck in the validation even if they do not exist in the DOM.
Any suggestions to escape this validation?
const schema = yup.object({
phone: yup.string().when('$exist', {
is: exist => exist,
then: yup.string().required(),
otherwise: yup.string()
})
})
schema.validate({ }, {
context: { exist: false }
}).catch(err => console.log(err))
I think it should be closed
cc @jquense
Most helpful comment