javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Tom picture Tom · Feb 13, 2013 · Viewed 182.4k times · Source

I am trying to write a regular expression to validate a password which must meet the following criteria:

  • Contain at least 8 characters
  • contain at least 1 number
  • contain at least 1 lowercase character (a-z)
  • contain at least 1 uppercase character (A-Z)
  • contains only 0-9a-zA-Z

I tried the following but it doesn't seem to work.

http://jsfiddle.net/many_tentacles/Hzuc9/

<input type='button' value='click' class='buttonClick' />
<input type='text' />
<div></div>

and...

$(".buttonClick").click(function () {

    if ($("input[type=text]").filter(function () {
        return this.value.match(/^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])([a-zA-Z0-9]{8})$/);
    })) {
        $("div").text("pass");
    } else {
        $("div").text("fail");
    }

});

Any ideas?

Answer

Minko Gechev picture Minko Gechev · Feb 13, 2013

Your regular expression should look like:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/

Here is an explanation:

/^
  (?=.*\d)          // should contain at least one digit
  (?=.*[a-z])       // should contain at least one lower case
  (?=.*[A-Z])       // should contain at least one upper case
  [a-zA-Z0-9]{8,}   // should contain at least 8 from the mentioned characters
$/