Home > Software engineering >  How to write Conditional regex?
How to write Conditional regex?

Time:01-02

I want to use Yup for validation. in a part of validation I have

const validationSchema = Yup.object({password: Yup.string().matches(passwordRegex, "passRegex")})

passWordRegex is a varibale that contains a regex :

const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{4,32}$/;

I have some booleans that determine that if for example small letter or big letter or speciall character is needed in password or not:

smallLetter = false
capitalLetter = true
specialChar = true 

now my regex ( passwordRegex variable) is not conditional . how can I write a regex (passwordRegex variable) conditional base on my Boolean variables

CodePudding user response:

Here's an example:

let passwordRegex = /^/;

if (smallLetter) {
  passwordRegex  = "(?=.*[a-z])";
}

if (capitalLetter) {
  passwordRegex  = "(?=.*[A-Z])";
}

if (specialChar) {
  passwordRegex  = "(?=.*[@$!%*?&])";
}

passwordRegex  = "[A-Za-z\d@$!%*?&]{4,32}$/";

const validationSchema = Yup.object({
  password: Yup.string().matches(passwordRegex, "passRegex")
});

CodePudding user response:

You could build the regex string you want and then create a proper RegExp object:

var input = "aB@3";
var smallLetter = false;
var capitalLetter = true;
var specialChar = true;
var number = true;

var regex = "";
if (smallLetter) regex  = "(?=.*[a-z])";
if (capitalLetter) regex  = "(?=.*[A-Z])";
if (specialChar) regex  = "(?=.*[@$!%*?&])";
if (number) regex  = "(?=.*[0-9])";

regex = "^"   regex   "[A-Za-z0-9@$!%*?&]{4,32}$";
var re = new RegExp(regex);
if (re.test(input)) {
    console.log(input   " => valid");
}

  • Related