Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

404
Vistas
How can we use an array of regex values in Yup, based on a form value

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?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda