Ask Your Question
2

How to validate a password that contains special characters using a regular expression in JavaScript?

asked 2021-05-30 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2021-11-22 08:00:00 +0000

plato gravatar image

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
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-05-30 11:00:00 +0000

Seen: 9 times

Last updated: Nov 22 '21