skip navigation

JavaScript: Form Validation: Passwords

A lot of websites now require registration, which means that users are either assigned a username and password, or get to select one. Here are some simple steps that will make the process a bit more secure.

Note: If the purpose of registration is to confirm that the person exists, with a given email address, then at the first instance you should email them a random password rather than having them choose their own. The code presented below would then be used when they were changing that password.

Use the "password" input type

Rather than using <input type="text"> you should always use <input type="password"> as this lets the browser (and the user) know that the contents of that field need to be secured. For a start, most browsers won't 'remember' the values entered in password fields as they do with other form elements.

Confirm password input

Because the password input type obscures the text typed, you should let the user confirm that they haven't made a mistake. The simplest way to do this is to have the password entered twice, and then compare the two.

Another method is to display what they've entered as part of a 'confirmation page'. The problem with that is that you could be making the password visible in the browser, browser cache, proxy, etc. Really, a password should never be displayed, or sent by email or other media unless you've taken appropriate measures (SSL connection, digital certificate, ...).

Enforcing 'strong' passwords

If you're concerned about security you should have some policy on what constitutes a valid password. Some common restrictions are:

  • at least n characters
  • combination of upper- and lower-case characters
  • one or more digits
  • not related to other user data (name, address, username, ...)
  • not a dictionary word

Leaving the last requirement for now (that really requires a server-side script), let's see what's possible using JavaScript.

Demonstration

The form below has three input fields, named in order: username, pwd1 and pwd2.

The code behind this form is as follows. If you're not sure how to place this on your page, you might need to read the preceding article on Form Validation, or view the HTML source of this page.

<script type="text/javascript"> 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; } if(form.pwd1.value != "" && form.pwd1.value == form.pwd2.value) { if(form.pwd1.value.length < 6) { alert("Error: Password must contain at least six characters!"); 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 = /[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; } </script>

expand code box

Remember that, as JavaScript isn't available in all browsers, you should user server-side scripting to validate all data before recording it in a database or text file.

Complex regular expressions

In the latest browsers - those that support JavaScript 1.5 (Firefox, Netscape 6/7, Mozilla, Safari and Opera 7) - you can use more powerful regular expressions. Older browsers will not recognise these patterns so the following is mostly useful for intranet rather than Internet applications.

The code presented above is fine in that it checks everything that we wanted to check, but it took a lot of lines of code to test each requirement individually and present different error messages. We're going to show you now how to do all the same tests using a single regular expression.

Consider the following:

var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/; var validPassword = re.test(input);

Note: The type of expression used here is called a 'look-ahead' which tries to match the contained regexp against the 'future' part of the string.

Translation:

  • matches a string of six or more characters;
  • that contains at least one digit (\d is shorthand for [0-9]);
  • at least one uppercase; and
  • at least one lowercase character.
inputresult of testreason
abcABCfalseno numbers
abc123falseno uppercase letters
abAB1falsetoo short
abAB12true-
Aa123456true-

If you're using a supported browser, you can use the form below to test the regular expression:


(input must contain at least one digit/lowercase/uppercase letter and be at least six characters long)

If you want to restrict the password to ONLY letters and numbers (no spaces or other characters) then only a slight change is required. Instead of using . (the wildcard) we use \w:

var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}$/; var validPassword = re.test(input);

Note: \w is shorthand for 'any letter, number or the underscore character'.

Again, you can use the form below to test this regular expression:


(as above, but this time ONLY letters and numbers are allowed)

As you can see, it's well worth learning the intricacies of regular expressions. They can be used not just in JavaScript, but also PHP, Perl, Java and many other languages. Some text editors (not just vi) also allow them when searching for or replacing text.

Related Articles

References

< JavaScript


User Comments and Notes

31 January 2007: Matthieu Turpault says:

I have tried the password "1h5gRgg" in the form used for password checking with complex regular expression. It seems that it is a valid password but the result is "Not Valid".

Strange, in my browsers that is identified as a valid password. Please note however that not all browsers support the more complex regular expressions involving look-ahead matching.


25 July 2007: Steve Thomas says:

This is some of the best code I have ever found on the web. Its great to see developers like you sharing this level of code. I will visit this site more often. Rock on!

Thanks Steve. When I started coding I relied a lot on other developers sharing code so I think it's only right to 'pay it forward'


19 May 2008: Babina says:

I tried the last code by typing asdf123 but it says that its not valid. Why is it so?

You need to include a capital letter as well to match the regular expression.


8 August 2008: Frank Severino says:

Kinda weird but if I enter 11wwZX into the 2 validation boxes it fails in IE 6 and 7 but works fine with Firefox, what's up with that????

Short answer - some/all versions of Internet Explorer do not support advanced regular expressions.


18 May 2010: George Inggs says:

GREAT code - this is a real time saver & combined with other validation techniques it has helped make our forms fairly bullet (read user) proof

Thanks heaps dude!!!


Send Feedback

Send Your Feedback (will not be published) (optional) CAPTCHA refresh copy the digits from the image into this box

[top]