React v16, formik, yup.
I am building a form in which a user must first select their state. this is a select field.
There is a second field for license, which will require different validation based on the state. I have a list of regex values that work fine if i add one directly to Yup. for exmaple:
export const form = Yup.object().shape({
state: Yup.string().required(),
license: Yup.string()
.when("required", {
is: (required) => required === true,
then: Yup.string()
.required("This field is required")
.matches(/^[0-9]{14}$/, "Please enter the ID in the proper format"),
}),
the above code, hardcoded regex, works great.
the question is how can i return a regex value in place of /^[0-9]{14}$/, from an array i have with all the regex values? when a user picks a state i want that regex to be switched out for their license.
I've tried adding functions (staying away from using arrow functions globally in the Yup validation schema due to issues with binding to this per their docs at Yup
another thing i've tried is adding a field in my form called "regex". this gets set when the user picks their state in the form. its an invisible field i set with Formik.setFieldValue which retains the regex, which i can call from the validation. doesn't work
license: Yup.string()
.when(["required", regex], {
is: (required) => required === true,
then: (regex) => Yup.string()
.required("This field is required")
.matches(regex, "Please enter the ID in the proper format"),
even when i try and create a new regexp w js, no luck
.matches(new RegExp(/^[0-9]{14}$/), "Please enter the ID in the proper format"),
it seems like i can get this work 1 time, but on state changes, the value on formik never gets re-evaluated.
to reiterate my question: How can i add dynamic regex for one field in Yup, based on a second field?