Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to allow either number or special characters

I have a regex to allow characters, atleast one number and special character text limit 8 to 15..

function validatePassword(password) {
    var re = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@.$!%*#?&])[A-Za-z\d$@.$!%*#?&]{8,15}$/i;
    return re.test(password);
}

Now I need to change this regex to accept either one number or one special character and same 8 to 15 limit

like image 448
Mohanraj S K Avatar asked Nov 24 '25 18:11

Mohanraj S K


1 Answers

You need to remove the lookahead requiring a digit, and move the \d to the lookahead requiring a special character:

var re = /^(?=.*[A-Za-z])(?=.*[\d$@.!%*#?&])[A-Za-z\d$@.!%*#?&]{8,15}$/;
                               ^^

If you do not need to require at least one letter, remove (?=.*[A-Za-z]).

Details:

  • ^ - start of string
  • (?=.*[A-Za-z]) - there must be at least 1 ASCII letter
  • (?=.*[\d$@.$!%*#?&]) - there must be at least 1 digit, or any one of the special chars in the class
  • [A-Za-z\d$@.!%*#?&]{8,15} - the string should only consist of letters, digits, and the special chars listed, from 8 to 15 occurrences.
  • $ - end of string.

Note that once you are using a-zA-Z, you do not need the /i case insensitive modifier.

Also, no ned to repeat $ in one and the same character class.

like image 61
Wiktor Stribiżew Avatar answered Nov 27 '25 09:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!