Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
143023864X_HT5.pdf
Скачиваний:
8
Добавлен:
21.02.2016
Размер:
7.98 Mб
Скачать

CHAPTER 8 USING THE FORMS API

// handle all invalid control notifications document.register.addEventListener("invalid", invalidHandler, true);

Now, whenever any of our form elements triggers a validation constraint, our invalidHandler will be called. In order to provide more subtle feedback than some of the prominent browsers do by default, we will color the label of the offending form field red. To do so, first we locate the <label> by traversing to the parent.

// find the label for this form control

var label = evt.srcElement.parentElement.getElementsByTagName("label")[0];

// set the label's text color to red label.style.color = 'red';

After setting the label to be a lovely red color, we want to stop the browser or any other handler from double handling our invalid event. Using the power of DOM, we call preventDefault() to stop any browser default handling of the event, and stopPropagation() to keep other handlers from getting access.

//stop the event from propagating higher evt.stopPropagation();

//stop the browser's default handling of the validation error evt.preventDefault();

And with just a few simple steps, we’ve provided a validated form with our own special interface validation code!

Practical Extras

Sometimes there are techniques that don’t fit into our regular examples, but which nonetheless apply to many types of HTML5 applications. We present to you some short, but common, practical extras here.

The Password Is: Validation!

One handy way to use the HTML5 Form validation support for custom validators is to implement the common technique of verifying passwords during a password change. The standard technique is to provide two password fields which must match before the form is submitted successfully. Here, we provide a way to utilize the setCustomValidation call to make sure that two password fields are matched before the form submits.

Recall that the customError validation constraint gives you a chance to set an error on a form control whenever the standard constraint rules do not apply. Specifically, one good reason to trigger the customError constraint is when the validation depends on the concurrent state of multiple controls, such as the two password fields here.

Because the ValidityState object is assumed to be live once a reference to it is obtained, it is a good idea to set the custom error on the ValidityState whenever the password fields are mismatched and immediately clear the error whenever the fields match again. A good approach for achieving this is to use the onchange event handler for the password fields.

<form name="passwordChange">

<p><label for="password1">New Password:</label>

<input type="password" id="password1" onchange="checkPasswords()"></p>

213

CHAPTER 8 USING THE FORMS API

<p><label for="password2">Confirm Password:</label>

<input type="password" id="password2" onchange="checkPasswords()"></p> </form>

As you can see here, on a trivial form with two password fields, we can register a function to execute every time the value of one of the passwords changes.

function checkPasswords() {

var pass1 = document.getElementById("password1"); var pass2 = document.getElementById("password2");

if (pass1.value != pass2.value)

pass1.setCustomValidity("Your passwords do not match. Please recheck that your new password is entered identically in the two fields.");

else pass1.setCustomValidity("");

}

Here is one way to handle the password matching. Simply grab the values of the two password fields, and if they do not match, set a custom error. For the sake of a validation routine, it is probably acceptable just to set the error on one of the two password fields. If they do match, set the empty string as the custom error to clear it; this is the specified way for removing a custom error.

Once you’ve got the error set on the field, you can use the approaches described earlier in this chapter to show feedback to the user and let her change the passwords to match, as expected.

Forms Are Stylin’

In order to help developers distinguish among form controls that have specific validation characteristics, the developers of CSS have helpfully added a set of pseudo-classes that can be used to set styles on form controls based on the state of their validity. In other words, if you desire form elements on your page to change style automatically based on whether or not they are currently complying with validation (or not), you can set these style pseudo-classes in your rules. These functions are very similar to longstanding pseudo classes such as :visited and :hover on links. Table 8-4 shows the new pseudo-classes proposed for the CSS Selectors Level 4 specification can be used to select form elements.

Table 8-4. CSS Pseudoclasses for HTML5 Form Validation

Type

Purpose

valid

This pseudo-class selects any form element that passes all validity rules. In other words,

 

this form element has state that is ready to be submitted.

invalid

This pseudo-class selects any form element that has errors or problems preventing it

 

from being submitted. Selectors with this class are useful for showing users errors on the

 

page.

in-range

This pseudo-class only selects elements such as inputs of type range where the current

 

value is safely between the minimum and maximum values.

out-of-

This pseudo-class selects elements with inputs that have values outside of the accepted

214