Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regular expression password validation having special characters

I am trying to validate the password using regular expression. The password is getting updated if we have all the characters as alphabets. Where am i going wrong ? is the regular expression right ?

function validatePassword() {     var newPassword = document.getElementById('changePasswordForm').newPassword.value;     var minNumberofChars = 6;     var maxNumberofChars = 16;     var regularExpression  = /^[a-zA-Z0-9!@#$%^&*]{6,16}$/;     alert(newPassword);      if(newPassword.length < minNumberofChars || newPassword.length > maxNumberofChars){         return false;     }     if(!regularExpression.test(newPassword)) {         alert("password should contain atleast one number and one special character");         return false;     } } 
like image 399
Srikanth Sridhar Avatar asked Aug 23 '12 10:08

Srikanth Sridhar


People also ask

How do you denote special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

Use positive lookahead assertions:

var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/; 

Without it, your current regex only matches that you have 6 to 16 valid characters, it doesn't validate that it has at least a number, and at least a special character. That's what the lookahead above is for.

  • (?=.*[0-9]) - Assert a string has at least one number;
  • (?=.*[!@#$%^&*]) - Assert a string has at least one special character.
like image 177
João Silva Avatar answered Oct 11 '22 21:10

João Silva