As of my last update in September 2021, yup, a schema validation library commonly used with React, does not directly support dynamic regular expressions out of the box. However, you can achieve dynamic regex matching in yup by using custom validation functions.

Here's how you can create a dynamic regex validation using yup:

  1. Install yup in your project if you haven't already:
npm install yup
  1. Import yup and create a custom validation function that takes the regular expression as a parameter:
import * as yup from 'yup'; const regexValidation = (regex) => yup.string().matches(regex, 'Invalid input'); // Example usage with a dynamic regex for email validation const emailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i; const emailSchema = yup.object().shape({ email: regexValidation(emailRegex), }); // Example usage with a dynamic regex for password validation const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/; const passwordSchema = yup.object().shape({ password: regexValidation(passwordRegex), });
  1. You can now use these schemas to validate your form inputs:
// Assuming formValues is an object containing form field values try { await emailSchema.validate(formValues); // Validation passed, handle form submission } catch (error) { // Validation failed, handle error }

By using a custom validation function, you can create dynamic regex matching in yup based on your specific needs. Just pass the appropriate regular expression to the regexValidation function when creating the schema.

Keep in mind that yup is often used in combination with form libraries like Formik, so the validation process might slightly differ depending on your setup. But the basic idea of creating custom validations with dynamic regular expressions remains the same.

Have questions or queries?
Get in Touch