60 Chapter 3—Intelligent Forms
<input type=email name=email
onchange="this.checkValidity();">
If you enter an invalid e-mail address and move away from the input field (either
with the Tab key or by clicking elsewhere in the browser), the browser (currently,
at least in Opera) returns an error message right away (refer to Figure 3.13). Error
handling becomes even more elegant if we attach a function for checking input
to the onchange event of all input elements:
window.onload = function() {
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++) {
if (!inputs[i].willValidate) {
continue;
}
inputs[i].onchange = function() {
if (!this.checkValidity()) {
this.style.border = 'solid 2px red';
this.style.background = '';
} else {
this.style.border = '';
this.style.background = 'lightgreen';
}
}
}
}
The familiar loop runs over all input elements, checking first whether the ele-
ment is available for validation. If willValidate does not return the value true,
the loop continues with the next element. Otherwise, an anonymous function is
assigned to the onchange event, calling the checkValidity function. this within
the anonymous function refers to the input element. If the validity check fails, the
element is surrounded with a red border; otherwise, the element’s background
is colored light green. Remember to reset the background color and border to an
empty character string to make sure the browser sets the formatting back to the
default value after the user has corrected an incorrect input. In Figure 3.14 you
can see how the checkValidity function generates an error message as a result
of incorrect time input.