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 63 Responses So Far. »

  1. Hi,

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

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

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

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

  5. 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.

  6. 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

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

  8. I enjoy reading through a post that can make people think.

    Also, thank you for allowing for me to comment!

  9. Attractive section of content. I simply stumbled upon your
    blog and in accession capital to assert that I
    get actually loved account your blog posts. Any way I’ll be subscribing for your feeds and even I fulfillment you access constantly quickly.

  10. However, it is absolutely essential to understand that the term HEPA should not equate to
    immediate trust of the purifier using it. If you have the opportunity, you are advised to read
    online reviews of multiple air purifiers. You will find more information that
    will help you as regards or other related oreck
    air purifier review, corinthian, neoair enviro plus air purifier neoair plus two, air
    filters purifiers reviews.

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

  12. 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:

  13. I know this website presents quality depending posts and other data, is there any other website which presents these things in quality?

Post a Response

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