Yup: how to validate field only when it exists? 聽

Created on 18 Nov 2020  路  2Comments  路  Source: jquense/yup

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?

Most helpful comment

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))

All 2 comments

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

Was this page helpful?
0 / 5 - 0 ratings