JavaScript Coder

Javascript password validation using regular expression

javascript form validation password validation regular expression validation

Suppose you want to validate whether the password has at least one number other than alphabetic characters.

Here is the regular expression to validate that condition

Check at least one number exists in the password

Here is the regular expression validation that confirms at least one number exists in the password

function validatePassword(pwd)
{
  var re = /^(?=.*\d).+$/
  
  return re.test(pwd)
}

This regular expression makes use of (positive lookahead assertion)[https://stackoverflow.com/a/1570916/1198745] (?= ). The expression simply means to match any character followed by a digit any nymber of matches.

Check at least one number and one Capital letter exists in the password and minimum length of 12 characters

function validatePassword(pwd)
{
  var re = /^(?=.*\d)(?=.*[A-Z])(.{12,50})$/
  
  return re.test(pwd)
}

The validation is enhanced a bit to add check for capital letter and a minimum length of 12 characters. (Remember that password streangth really depends on the length of the password )

See Also