HTML5 Guidelines for Web Developers

(coco) #1
3.4 Client-Side Form Validation 59

WebKit-based browsers, such as Google Chrome or Safari, currently support the
validation but do not display an error message. They place a border around the
invalid field and position the cursor in the field to at least provide some indica-
tion that something is not quite right.


Despite all the euphoria about client-side validation of form input, you should
not forget that this step cannot replace server-side control. A potential attacker
can bypass these mechanisms with very little technical effort.

3.4.1 The “invalid” Event


During form validation, elements with an invalid content trigger the event in-
valid. We can use this to react individually to incorrect values:


window.onload = function() {
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++) {
inputs[i].addEventListener("invalid", function() {
alert("Field "+this.labels[0].innerHTML
+" is invalid");
this.style.border = 'dotted 2px red';
}, false);
}
}


After loading the page, a list of all input elements is generated (as in the ex-
ample in section 3.3.5). An event listener is added to each element and deals
with the error. In our example it opens an alert window, and the element is
marked with a red-dotted border. The label of the input element is used as text
in the alert window.


This approach is not ideal in forms with many input fields. The user must click
the OK button for each incorrect input and then find the appropriate field in the
form and fill in the details again. Sometimes, it would be more useful if the user
could be notified immediately of invalid input while filling in the field. We will
try this in the next section.


3.4.2 The “checkValidity” Function


To trigger the validation of an input element, the checkValidity function for that
element is called. But you can also start “manually” what would normally hap-
pen when the form is submitted:


NOTE
Free download pdf