JavaScript: Form Validation: PasswordsA 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. Guidelines for Secure Password InputUse the "password" input typeInstead of <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. Your password won't appear on the screen as you type and most browsers also won't 'remember' the values entered in password fields as they do with other form elements. Confirm password inputBecause 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 check that they are identical. 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' passwordsIf you're concerned about security you should have some policy on what constitutes a valid password. Some common restrictions are:
Leaving the last requirement for now (that really requires a server-side script), let's see what's possible using JavaScript. Basic DemonstrationThe 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>
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. You might also want to spice up your forms using some HTML5 Form Validation techniques. Complex regular expressionsIn 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: <script type="text/javascript">
// at least one number, one lowercase and one uppercase letter
// at least six characters
var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/;
var validPassword = re.test(input);
</script>
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:
If you're using a supported browser, you can use the form below to test the regular expression: 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: <script type="text/javascript">
// at least one number, one lowercase and one uppercase letter
// at least six characters that are letters, numbers or the underscore
var re = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{6,}$/;
var validPassword = re.test(input);
</script>
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 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
ReferencesSend Feedback |
||||||||||||||||||
|
© Copyright 2012 Chirp Internet
- Page Last Modified: 18 September 2011
|
||||||||||||||||||
User Comments and Notes
Matthieu Turpault 31 January, 2007
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.
Steve Thomas 25 July, 2007
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'
Babina 19 May, 2008
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.
Frank Severino 8 August, 2008
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.
Gladson Jacob 17 September, 2008
Beautiful coding. But what to do, if I have to satisfy the following validation?
The password must be at least 8 characters long.
The password must contain characters from at least three of the following classes of Unicode:
Latin uppercase letters A, B, C, ... Z
Latin lowercase letters a, b, c, ... z
Westernized arabic numerals 0, 1, 2, ... 9
Non-alphanumeric symbols ? ! # ... etc
George Inggs 18 May, 2010
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!!!
pk 29 December, 2010
good advice.
i just removed the password registration boxes.
will send random.
thank you very much.