I am currently learning react and encountered an issue. I have a contact info collection page which may display the country code and phone number based on a boolean variable in the form. I am passing it in the context to the validation schema. My schema looks like:
export const contactValidation = yup.object().shape({
phoneNumber: yup
.string()
.required('this is required')
.max(10, 'only 10 characters allowed')
.matches(aSimpleRegex, 'the format is incorrect'),
countryCode: yup.object().required('contact country required'),
});
This is not always the case, because I am controlling the display of countryCode based on a boolean variable in the form. I can access the context by doing something like:
const context = this.options.context as ContactContext;
context.countryCodeEnabled;
I would like to use this and only validate the countryCode field when context.countryCodeEnabled is true. Also when it is true, I want to use a different REGEX in the .matches option of phoneNumber.
The issues I am facing with this:
- I am unable to define a const inside the
yup.object().shape - If able to access it somehow, how do I use it to control the validation and change the regex as well?
Thank you so much for your help in advance.