Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To validate a password that contains special characters using a regular expression in JavaScript, you can use the following code:

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

This regular expression pattern checks for the following criteria:

  • At least one special character: (?=.*[!@#$%^&*])
  • At least one lowercase letter: (?=.*[a-z])
  • At least one uppercase letter: (?=.*[A-Z])
  • At least one numerical digit: (?=.*\d)
  • Minimum of 8 characters: .{8,}

To use this function, simply pass your password string as an argument:

console.log(validatePassword("My$tr0ngP@$$w0rd")); // true
console.log(validatePassword("mypassword")); // false