imin
imin

Reputation: 4578

Symbols as optional character in regex

Currently here's how I do my regex:

var myPassword = $('#reg_password').val();
if (myPassword.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/)) {}

From the regex above, myPassword should contain at least 1 digit, 1 upper case and lower case. Now I want to add symbols as optional. I tried adding

([@$!%*#?&]?)

at various places in my regex above but it doesn't work...

Upvotes: 0

Views: 45

Answers (2)

Maria Ivanova
Maria Ivanova

Reputation: 1146

You can simply add the symbols in the [0-9a-zA-Z] like this:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z@$!%*#?&]{8,}$/

Upvotes: 0

Bergi
Bergi

Reputation: 664620

Don't try to put everything in a single regex. Just test your requirements separately!

if (myPassword.length >= 8 &&
    /[a-z]/.test(myPassword) &&
    /[A-Z]/.test(myPassword) &&
    /\d/.test(myPassword) &&
    /[@$!%*#?&]/.test(myPassword)) {
}

Upvotes: 2

Related Questions