Flagrant Badassery

A JavaScript and regular expression centric blog

JavaScript Password Validation

Since I've seen tons of password validation help requests on regexadvice.com (where I hang out from time to time), I've written up a more general-purpose JavaScript password validation function. It's reasonably straightforward, and covers the validation requirements I've most frequently encountered. Plus, if it doesn't handle your exact needs, its functionality can be augmented by passing it custom functions and regular expressions.

Here are the validation types supported out of the box. All are optional, which means that all passwords are allowed by default.

  • Minimum and maximum length.
  • Minimum n lowercase characters (a–z).
  • Minimum n uppercase characters (A–Z).
  • Minimum n combined a–z and A–Z characters.
  • Minimum n numeric characters (0–9).
  • Minimum n special characters (characters other than a–z, A–Z, and 0–9).
  • Ban particular words (tested case-insensitively).
  • Ban n-length character sequences (e.g. "abc", "XYZ", or "789", with a sequence length of 3; does not apply to special characters).
  • Ban n-length qwerty character sequences (e.g. "qwerty" or "asdf", with a sequence length of 4; does not apply to special characters).
  • Ban sequential, identical characters (e.g. "aa" or "!!").
  • Use custom regular expressions (tested using RegExp.prototype.test) and functions (the password is provided as the first argument, and a Boolean value is expected in return).

Here's an example of how it can be used:

var password = "password";
var passed = validatePassword(password, {
	length:   [8, Infinity],
	lower:    1,
	upper:    1,
	numeric:  1,
	special:  1,
	badWords: ["password", "steven", "levithan"],
	badSequenceLength: 4
});
// passed: false

The above requires that password is at least eight characters long; has at least one lowercase, uppercase, numeric, and special character; doesn't include the words "password", "steven", or "levithan"; and doesn't include an alphanumeric sequence four or more characters in length (e.g. "1234").

Here's the code (there are no external library dependencies):

/*
	Password Validator 0.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT License
*/

function validatePassword (pw, options) {
	// default options (allows any password)
	var o = {
		lower:    0,
		upper:    0,
		alpha:    0, /* lower + upper */
		numeric:  0,
		special:  0,
		length:   [0, Infinity],
		custom:   [ /* regexes and/or functions */ ],
		badWords: [],
		badSequenceLength: 0,
		noQwertySequences: false,
		noSequential:      false
	};

	for (var property in options)
		o[property] = options[property];

	var	re = {
			lower:   /[a-z]/g,
			upper:   /[A-Z]/g,
			alpha:   /[A-Z]/gi,
			numeric: /[0-9]/g,
			special: /[\W_]/g
		},
		rule, i;

	// enforce min/max length
	if (pw.length < o.length[0] || pw.length > o.length[1])
		return false;

	// enforce lower/upper/alpha/numeric/special rules
	for (rule in re) {
		if ((pw.match(re[rule]) || []).length < o[rule])
			return false;
	}

	// enforce word ban (case insensitive)
	for (i = 0; i < o.badWords.length; i++) {
		if (pw.toLowerCase().indexOf(o.badWords[i].toLowerCase()) > -1)
			return false;
	}

	// enforce the no sequential, identical characters rule
	if (o.noSequential && /([\S\s])\1/.test(pw))
		return false;

	// enforce alphanumeric/qwerty sequence ban rules
	if (o.badSequenceLength) {
		var	lower   = "abcdefghijklmnopqrstuvwxyz",
			upper   = lower.toUpperCase(),
			numbers = "0123456789",
			qwerty  = "qwertyuiopasdfghjklzxcvbnm",
			start   = o.badSequenceLength - 1,
			seq     = "_" + pw.slice(0, start);
		for (i = start; i < pw.length; i++) {
			seq = seq.slice(1) + pw.charAt(i);
			if (
				lower.indexOf(seq)   > -1 ||
				upper.indexOf(seq)   > -1 ||
				numbers.indexOf(seq) > -1 ||
				(o.noQwertySequences && qwerty.indexOf(seq) > -1)
			) {
				return false;
			}
		}
	}

	// enforce custom regex/function rules
	for (i = 0; i < o.custom.length; i++) {
		rule = o.custom[i];
		if (rule instanceof RegExp) {
			if (!rule.test(pw))
				return false;
		} else if (rule instanceof Function) {
			if (!rule(pw))
				return false;
		}
	}

	// great success!
	return true;
}

You can download it here.

Lemme know if you have any feature requests or other suggestions about how to improve it, or if you need help writing custom rules for it.

There Are 57 Responses So Far. »

  1. Thanks for the comment. I’m looking forward to posting more substantive info.

  2. That’s great to hear, Dean!

    For the record, based on Dean’s email address I assume he’s Dean Hachamovitch, General Manager of the IE team, and that his response was regarding a comment where I poked fun at the apparent lack of humor of some other commenters on the IE blog and mentioned that I was looking forward to seeing him keep his promise regarding more IE8 info in the near future.

  3. Hi. I use Passpack to store my password online (http://www.passpack.com). During registration, for example, they checks your password measuring the quality in bit. Your password must be at least 64-bit quality. Maybe, you could have a look at their approach. It is very interesting.
    Argo

  4. Hmm… their password rating system is quite pretty. However, it’s not equivalent to this for several reasons. For one, it’s designed exclusively for their site and they make it very clear that the code is not open source. Secondly, it gives you a sliding scale of “password quality,” rather than a pass/fail system. That’s good if you’re just trying to assist users with selecting a good password, but not as good if you’re trying to meet pre-defined business requirements about password validation. Third, their system relies on password length and basic character types, but doesn’t do any of the more fancy kinds of validation you can see here.

    I’d considered implementing a quality score system, but that would significantly complicate things considering that the goal of this script is to let people who use it decide how they measure password strength, in order for it to be usable in more cases.

  5. Well, of course this is only one half of the whole thing: at serverside you´ll need to do the same thing in your preferred serverside language. That´s why I love ASP.NET Ajax – just define the regex you wanna use and the framework creates the js for you, while you´re focussing on writing the server-side part of it. Frameworks rock!

  6. How would the sequential identical check be modified to allow 2, but not 3 or more characters?

  7. @JKatelman, here’s one way:

    validatePassword(pw, {custom:[/^(?!.*(.)\1\1)/]});

  8. Thanks for the response. I should have been a little more clear in what I was asking. The condition /([\S\s])\1/.test(pw) is a boolean for not allowing two characters. Is there a similar way to have a single condition that acts like a boolean for three characters?

  9. Yes. /([\S\s])\1\1/. But why would you fork the code for something like this when it makes it easy to provide custom validation rules? As an alternative to the standalone regex in my last comment, you could pass in the custom function function(pw){return !/([\S\s])\1\1/.test(pw);}.

  10. can u please tell what is mean by option on that code what we need to initialize for that?

  11. Please help me with the regular expression for the password policy mentioned below:-
    The password length should at least be 8 characters. It should be a combination of at least any two of the given sets.
    a. Set of alphabets a-z, A-Z
    b. Set of numerics 0-9
    c. Set of special characters ~!@#$ etc.

  12. @tuttu, this function doesn’t support x out of y rule validation (apart from accepting a custom function that does it itself). Better to bypass the function:

    var valid = 8 <= pw.length && 2 <= (
        /[a-z]/i.test(pw) +
        /[0-9]/.test(pw) +
        /[~!@#$]/.test(pw)
    );
  13. Very nice Steven. Keep up the good work.

  14. Hi Steven,

    Can you help me with the following validation requirement.
    Min 8 characters.
    Atleast 1 Uppercase character
    Atleast 1 Numeric
    Atleast 1 Special character

    Thanks in advance…

  15. Hi Steven,

    I’m trying to use the password validation into my assignment for school, but I am having a hard time turning this validation to have a error message directly onto the form, instead of a prompt box.

    What should I do?

  16. I am a complete newbie. How do you apply/append/use this code? Is there a sample html/php snippet I can use?

    for example:

    thanks!

  17. Hello everybody.

    I have a question. How to use validatePassword function if I need to check whether first character is number or not?

    Thanks!

  18. Hi Steven,
    Can you please help me with this validation.

    Should contain at least one element from each of the following
    A)Alphabet (A-Z, a-z)
    B)Numbers (0-9, special characters (~!@#$%^&*()_+[]{}:;)

    Regards,
    Bhagya

  19. hey but i want to check for white spaces also..
    password should not accept spaces rite..??

  20. The code provided for password verification is good but i need a code bit simpler and precise and plz provide me with demo also,as i m fresher to javascript.

  21. The password code validate is very good. I have to implement the no sequential and repeated letters or numbers in the password. I tried with the following code (/([\S\s]){3}/.test(pw)) and didn’t satisfy the above condition.

  22. Nice article…

  23. Thank you for this script. It works really fine. But one question: How would the sequential identical check be modified to allow only a maximum number of characters?

  24. this is my code.but it does not work in windows.my platform is linux
    kindly reply me soon

  25. Love this JavaScript! Thank you for creating it, as well as making it available! Have you thought about expanding the “badWords” check to include a dictionary, rather than just a handful of words? Although it might take to long? What are your thoughts?

  26. Thanks much for creating this. I had to write a voicemail password reset request form for my users that required the ability to submit either web application passwords or phone passwords, the latter of which could obviously be numbers only. This worked very well.

  27. I want to define password policy in javascript with min 6 char length and atleast 1 number or special character.
    what would be the java script code for it.

  28. validation for pin must not be allow given below conditions

    6 rising consecutive numbers(e.g 123456,456789 etc)
    6 Descending consecutive numbers (eg. 654321,987654)
    All same digit (eg 111111,222222)
    Same digit appearing 3 or more time in pin code (eg:121212,1111432)

  29. Thanks a million for this, I have been fighting with password validation over 10 hours now and you simply have the solution. You saved me from some serious trouble.

  30. Thanks for the script, Can I modify your code ie i want to make replica of your code so that it can be more of Object Oriented ???
    Although there is MIT License associated still I want to use it for commercial purpose so can I ???

  31. what bllll kcuf ffffffff

  32. help….

    i love your script.. but i cant get it to work. I am a novice when it comes to javascript. For testing, I tookout all of the parameters of the function.

    here is my code…

    function ValidatePW()
    {
    validatePassword()
    }

    I get the error: Microsoft JScript runtime error: Object expected.

    I feel stupid because no one else has got the error so I know I am doing somthing wrong.

    Thanks in advance.

  33. me again.. i fixed my problem. Yeah me. Now, I want to offer another check for you and your readers.

    If is badRepeatLength, so you can’t have the same character repeat itself x number of times.

    if (o.badRepeatLength)
    {
    for (i = 0; i < pw.length; i++)
    {
    seq = pw.substring(i, o.badSequenceLength + i);
    allthesame = true;
    chr = seq.charAt(0);

    if (seq.length == o.badSequenceLength)
    {
    for (c = 0; c < seq.length; c++)
    {
    if (chr != seq.charAt(c))
    {
    allthesame = false;
    break;
    }

    chr = seq.charAt(c);
    }

    if (allthesame)
    {
    return false;
    }
    }
    }
    }

  34. forums built above the same subject areas? Many thanks!

  35. Hi,
    Thanks for this bit of code. It’s nicely written.
    I am getting back into Javascript after 9 years.

    I am getting an error on line 41 character 9;

    Webpage error details

    Message: Object doesn’t support this property or method
    Line: 41
    Char: 9
    Code: 0
    URI: http://localhost:54458/Scripts/validatePassword.js

    which relates to this;

    // enforce lower/upper/alpha/numeric/special rules
    for (rule in re) {
    –> if ((pw.match(re[rule]) || []).length < o[rule])
    return false;
    }

    I will try and debug myself but if you have any ideas?

    Thanks,
    Adrian

  36. good

  37. Thank you for nice work, Steven!

  38. Hi,
    Great work! If you should modify the code to prohibit the use of special characters, numeric, etc…

    I think maybe, the code could be modified, so that default value of any option (i.e. when the rule does not apply) could be -1 and if numeric/special characters are not allowed at all, then the value is 0 (or vice-versa 0=default, -1=not allowed)

  39. Solved it!

    Instead of this:
    // enforce lower/upper/alpha/numeric/special rules
    for (rule in re) {
    if
    ((pw.match(re[rule]) || []).length < o[rule])
    return false;
    }

    I rewrote the code to this:

    // enforce lower/upper/alpha/numeric/special rules
    for (rule in re) {
    if
    ((((pw.match(re[rule]) || []).length > 0) && (o[rule] == -1)) ||
    ((pw.match(re[rule]) || []).length < o[rule]))
    return false;
    }

    And it worked!
    Now, if I want to prohibit some characters, e.g. special characters, I just call the function with the option

    special: -1
    And I can do the same for numeric, uppercase, lowercase and alpha

  40. can you help to incorporate check where last character of the password cannot be special characters?

    i think i can amend it myself but i’m a beginner of javascript and boss want me to add this for certain thing so have to start learn.

  41. its nice one but i need some validations like pincode it should not start with 0 and min 6 characters, phone number starts with 7 or 8 or 9 but min 10 characters and date validations it should not support post dates i mean tomorrow’s date..

  42. please Please help me with the java script code for the password policy mentioned below:-
    The password length should be only 8 characters. It should be a combination of the given sets.
    a. Set of alphabets a-z, A-Z
    b. Set of numerics 0-9
    c. Set of special characters ~!@#$ etc

  43. Hi Steven,
    Can you please help me with this validation.

    Should contain at least one element from each of the following
    A)Alphabet (A-Z, a-z)
    B)Numbers (0-9, special characters (~!@#$%^&*()_+[]{}:;)
    c)Maximum Length 20 Charecters

    Thanks & Regards
    Naveen

  44. I found this code just great and have managed to use it in my password validation. Thanks for your efforts they are most appreciated.

  45. Hi,

    Please help me in doing this.

    Should accept the following conditions
    4 alphabets (A-Z, a-z)
    1 numbers (0-9)
    1 special characters (~!@#$%^&*()_+[]{}:;)
    Min 6 and Max 10 Characters

    even i tried with the bellow expression but it allows only few special characters only
    /((?=.*\d)(?=.*[a-zA-Z])(?=.*[@#$%]).{6,10})/

    …..
    Thanks in advance

  46. Thank you so much! Awesome validation method. Easy to understand and to expand/modify for any situation.

  47. Hi Steve,
    I’m sure hoping you can help me on this one. Needing the validation for new passwords followed by encryption before they to go through the wire to the perl end of things and in search I found your script at https://blog.stevenlevithan.com/archives/javascript-password-validator. The encryption thing is already taken care of and I can take care of the perl end of things but am totally lost with javascript. I just need to know what to do to implement your code into a page and be able to call the errors either compiled in an alert box or text messages. While I understand that people can disable javascript I don’t think it will be that serious of an issue and the project is not high end enough to warrant an ssl certificate. Pretty much I just want to make it possible for users to reset their password either through editing or via a lost password function requiring a change while at the same time atleast making it a little harder for the mischief minded. This is what I have working so far:

    <html>
    <head>
    <script src=”sha512.js”></script>
    <title>Crypt that Word</title>
    </head>
    <body>
    <form method=”post”action=”http://lost.com”>
    <p>Password 1:<br />
    <input type=”password” name=”newpassword1″></br>
    Rewrite It<br>
    <input name=”cryptit”onkeyup=”document.getElementById(‘hash’).value = SHA512(this.value)” size=”32″ type=”text” />
    <input name=”newpassword2″ id=”hash” readonly=”readonly” size=”64″ type=”hidden” />
    <br /><input type=”submit”>
    </form>
    <script>hash();</script>
    </body>
    </html>

    newpassword2 is the encrypted verion of cryptit which is sent to the server for inserting to the db.

    ~Dave

  48. I need to check whether the password consists of text, number, and special characters, how to validate these conditions… Pls guide with explanation and coding.. Thank you..

  49. Hi,

    This works fine except that spaces are also allowed in this.Can i fix this.

  50. Whitespaces will be invalidated if you add the /[\s]/g within the custom regexes declaration.

  51. My comment above is wrong, the correct regexp is /^\S+$/g

  52. Hi. Good job.
    Thanks a lot for share.

  53. Thanks for this wonderful code. I need further help to validate sign-in form, checking input against pre-established username and password. Can you help with the code to accomplish this? Any help will be appreciated.

  54. Can anyone help me in Write an “active password checker” code using CSS/HTML and JavaScript. Active password checker must:
    1.Make sure that the selected password is at least 8 characters in length.
    2.Use a dictionary of bad passwords and a rule base, so that you exclude passwords that match known “bad” words. For the words in the bad password dictionary, you may construct your own dictionary as long as it contains at least ten entries which are bad passwords.

    Or

    Someone can help me in modifying above password validation code by Steven

    Thanks in advance

  55. Worked like a charm. Thanks for saving lot of time!!

  56. I can’t download the script
    I’m getting error 404 not found

  57. I’m writing a password validation in java using RegX and I’m stuck on two conditions:

    1- no three sequential characters like ( 123,456,789,abc,def,lmn,opq)

    2-password cannot contain the following words like (London, Volvo)

    below is the script so far : Any help will be appreciated so much

    function checkForm(form)

    {

    if(form.username.value == “”) {

    alert(“Error: Username cannot be blank!”);

    form.username.focus();

    return false;

    }

    re = /^\w+$/;

    if(!re.test(form.username.value)) {

    alert(“Error: Username must contain only letters, numbers and underscores!”);

    form.username.focus();

    return false;

    }

    re = /.{8}/;

    if(form.pwd1.value != “” && form.pwd1.value == form.pwd2.value)

    if(!re.test(form.pwd1.value)) {

    alert(“Error: Password must contain eight characters Only, Try again!”);

    form.pwd1.focus();

    return false;

    }

    if(form.pwd1.value !== “” && form.pwd1.value == form.pwd2.value) {

    if(form.pwd1.value.length >= 9) {

    alert(“Error: Password must contain eight characters Only, Try again!”);

    form.pwd1.focus();

    return false;

    }

    if(form.pwd1.value == form.username.value) {

    alert(“Error: Password must be different from Username!”);

    form.pwd1.focus();

    return false;

    }

    re = /^(?:(?!(.)\1\1.*).)*$/;

    if(!re.test(form.pwd1.value)) {

    alert(“Error: password must not contain the same charactrer more than twice in arow (AAA, 222)!”);

    form.pwd1.focus();

    return false;

    }

    re = /[0-9]/;

    if(!re.test(form.pwd1.value)) {

    alert(“Error: password must contain at least one number (0-9)!”);

    form.pwd1.focus();

    return false;

    }

    re = /[a-z]/;

    if(!re.test(form.pwd1.value)) {

    alert(“Error: password must contain at least one lowercase letter (a-z)!”);

    form.pwd1.focus();

    return false;

    }

    re = /[A-Z]/;

    if(!re.test(form.pwd1.value)) {

    alert(“Error: password must contain at least one uppercase letter (A-Z)!”);

    form.pwd1.focus();

    return false;

    }

    } else {

    alert(“Error: Please check that you’ve entered and confirmed your password!”);

    form.pwd1.focus();

    return false;

    }

    alert(“You entered a valid password: ” + form.pwd1.value);

    return true;

    }

    Password Validation

    Username:

    Password:

    Confirm Password:

Post a Response

If you are about to post code, please escape your HTML entities (&amp;, &gt;, &lt;).