It is good practice to subscribe to events such as onkeyup
, and onkeychange
from JavaScript and not embed the event listeners as attributes in the elements themselves. This gives a good separation of logic and content. Facebook most likely has some external (or internal) JavaScript code that subscribes to the onkeyup
, onkeypress
, and onblur
events of its input fields.
If you want to learn how this works, I suggest you read QuirksMode.org's Introduction to Events, and Advanced Event Registration Models. Because of the differences between IE's model and the standard, you're better off using a JavaScript library to do this work for you.
A few examples are jQuery, YUI, Prototype, and Dojo (and there are more that I can't think of at the moment). I suggest you pick a framework, and become familiar with it. It will make JavaScript development much easier.
Here is some working example code in jQuery that you can use to get up and running very quickly. A full working example can be found here: http://jsbin.com/obama. If you want it done "right", you should use a validation framework that handles the logic for you. Here's an example of a working jQuery validation framework, and here is the plugin it was written in.
(function() {
$(document).ready(function() {
$("#password").blur(function() {
});
function validatePasswordsMatch() {
var $pwd = $("#password");
var $confirm = $("#confirmPassword");
if ($pwd.val().length > 0 && $confirm.val().length > 0 && $pwd.val() != $confirm.val()) {
$("#match").text("Passwords do not match.");
$confirm.keyup(validatePasswordsMatch);
$pwd.keyup(validatePasswordsMatch);
console.log('alert bad');
} else {
$("#match").text("");
console.log('alert');
$confirm.unbind('keyup', validatePasswordsMatch);
$pwd.unbind('keyup', validatePasswordsMatch);
}
}
function validatePasswordLength() {
var $pwd = $("#password");
if ($pwd.val().length < 6) {
$("#lengthMsg").text("Password does not meet length requirement.");
// Bind to keypress so the validator re-validates as the user types when the text box gains focus.
$pwd.keypress(validatePasswordLength);
} else {
$("#lengthMsg").text("");
$pwd.unbind('keypress', validatePasswordLength);
}
}
$("#password").blur(validatePasswordLength).blur(validatePasswordsMatch);
$("#confirmPassword").blur(validatePasswordsMatch);
});
})();