25.02.2013 Views

Peter Lubbers - Pro HTML 5 Programming

Pro HTML 5 Programming

Pro HTML 5 Programming

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

184<br />

CHAPTER 7 ■ USING THE <strong>HTML</strong>5 FORMS API<br />

value, the browser might present an error message to the user that “This field requires a value.” Once<br />

supported, this is the text string that would be returned by the validationMessage field, and it would<br />

adjust according to the current state of validation on the control.<br />

Validation feedback<br />

On the subject of validation feedback… one topic we’ve avoided thus far is how and when the browser<br />

should present the user with feedback on a validation error. The specification does not dictate the terms<br />

of how the user interface is updated to present an error message, and existing implementations differ<br />

fairly significantly. Consider the case for Opera. In Opera 10.5, the browser indicates that a validation<br />

error has occurred by marking the field in error with a popup message and a flashing red field.<br />

In contrast, the Google Chrome browser only navigates to the offending field and puts the focus<br />

there when an error is found. What is the correct behavior?<br />

Neither is specified. However, if you would like to take control of the feedback shown to the user<br />

when a validation error occurs, there is an appropriate handler for you to do so: the invalid event.<br />

Whenever a form is checked for validity—either due to the form being submitted, or due to the<br />

checkValidity function being called directly—any form in an invalid state will be delivered an invalid<br />

event. This event can be ignored, observed, or even cancelled. To add an event handler to a field which<br />

will receive this notification, add some code similar to Listing 7-2:<br />

Listing 7-2. Adding event handlers for invalid events<br />

// event handler for "invalid" events<br />

function invalidHandler(evt) {<br />

var validity = evt.srcElement.validity;<br />

// check the validity to see if a particular constraint failed<br />

if (validity.valueMissing) {<br />

// present a UI to the user indicating that the field is missing a value<br />

}<br />

// perhaps check additional constraints here…<br />

// If you do not want the browser to provide default validation feedback,<br />

// cancel the event as shown here<br />

evt.preventDefault();<br />

}<br />

// register an event listener for "invalid" events<br />

myField.addEventListener("invalid", invalidHandler, false);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!