HTML5 Validation - HTML and CSS - HTML5, JavaScript and jQuery (Programmer to Programmer) - 2015

HTML5, JavaScript and jQuery (Programmer to Programmer) - 2015

Part I HTML and CSS

Lesson 8 HTML5 Validation

When the user submits a form, it is common to perform validation of the data the user has entered within the browser. This allows any issues, such as missing data, to be resolved before the form is sent to the server, and generally provides a superior user experience.

Form validation has traditionally been performed with JavaScript: In fact, until recently this was the most common use of JavaScript within web pages. HTML5 provides built-in form validation, and allows fields to be validated based on attributes added directly to the fields themselves. This lesson will look at how you can enable validation on the form created in Lesson 6.

The HTML5 form validation specification is not perfect—it lacks some of the rules you would expect in a complete validation framework. It does, however, have the advantage of being a native solution and is very easy to use. It is therefore necessary to decide at the outset of a project whether HTML5 validation is sufficient, or whether you will use one of the many JavaScript libraries available—for instance, jQuery validation.

Adding Validation Rules

This section will add form validation to the contacts.html web page as it stood at the end of Lesson 7. If you would like to follow along, open this file now, or download it from the book's website.

The most common form of validation is specifying that a field is mandatory. You can indicate that the user is required to provide a value for a field by simply adding the required attribute to it. This is a Boolean attribute, so it does not require a value:

<input required autofocus autocomplete="off"

name="contactName" id="contactName" type="text" />

If you open this page in Chrome, you will not initially notice any difference. If you now press Enter in the Contact name field without first providing a value, however, you will receive the message shown in Figure 8.1.

image

Figure 8.1

Unfortunately, you only receive this error when you press Enter in the field, or press the Submit button without providing a value for the field. Tabbing out of the field is not enough to trigger the validation message.

With field validation, it is generally better to provide immediate feedback to the user when a field is invalid. Users can become frustrated when told a number of fields are invalid when they submit the form because they need to locate each of these individually and provide values.

One way to provide immediate feedback to a user is via a pair of CSS pseudo-classes called valid and invalid. In order to demonstrate these, add the following to the contacts.css:

.validated:invalid {

background:#FAC3C9;

}

.validated:valid {

background:#BDF0A8;

}

These rules will set the background color of an element a shade of pink if it is invalid or a shade of green if it is valid.

Notice that you have specified that these rules only apply if the element is tagged with the validated class. Technically, all input fields can be valid or invalid, even ones with no rules applied to them, such as submit buttons. Rather than have these appear green, you will explicitly add a class when you want an element to use these styles. Therefore, add the validated class to the input field:

<input required autofocus autocomplete="off"

name="contactName" id="contactName" class="validated" type="text" />

If you reload the web page it should initially display with the pink background, as shown in Figure 8.2.

image

Figure 8.2

If you now type some text into the field, you will notice that it immediately turns green.

Another common validation rule for a field relates to the number of characters it can contain. It is common to specify both a minimum and a maximum number of characters for a field.

The HTML5 specification specifies two new attributes called min and max that look promising in this respect. Unfortunately these are only useful for validating that a number is between a minimum and maximum value; they are of no use at all for textual data.

The specification does provide an attribute called maxlength that can be used to control the maximum number of characters that can be added to a field. This works by physically preventing the user from typing into the field when this limit is reached. The only way to perform validation for a minimum length, however, is to use the pattern attribute. This accepts a regular expression. For example:

<input required autofocus autocomplete="off" name="contactName"

type="text" class="validated" id="contactName" pattern=".{5,100}"/>

Note

Regular expressions are a formal language for expressing textual patterns and checking if a string of text matches this pattern. In this particular case the “.” matches any single character, while the two numbers in curly brackets specify that this must occur between 5 and 100 times. I will not explain regular expressions in any more detail in this book, but there are many online resources available for learning more.

If you reload the web page and start typing into it, you will notice that the background does not turn green until you type the fifth character. Additionally, if you type more than 100 characters, it will turn pink again.

You can add similar validation to the phone number field:

<input required pattern=" [0-9() ]{5,15}" placeholder="Include area code"

name="phoneNumber" type="tel" id="phoneNumber" class="validated"/>

In this case, you ensure that the number of characters is between five and fifteen, and you are limiting the characters the field will accept to numbers, brackets, and spaces.

When you come to the email address field, things become slightly more interesting. If you simply add the required attribute, you may be pleasantly surprised by the resulting 'margin-bottom:0cm;margin-bottom:.0001pt;line-height: normal;vertical-align:baseline'><input required name="emailAddress" id="emailAddress" type="email" class="validated" />

If you start typing into the field, you will notice that it does not turn green until you enter the @ symbol. Because the type has been specified as email, the browser automatically checks that the value adheres to the rules for email addresses.

For the select box, you also want to ensure that the user selects a genuine value, not the first entry from the list. You can achieve this as follows:

<select required name="companyName" id="companyName" class="validated">

<option value="">Please select</option>

<option value="1">ABC Incorporated</option>

<option value="2">XZY Ltd</option>

<option value="3">ACME iInternational</option>

</select>

Notice that, in addition to setting the select box to required, you have also specified that the value of the first option is an empty string. This does not count as a value; therefore, the select will turn green only if the user selects another value from the list of options.

Finally, for the notes field, you will simply specify a maximum number of characters that can be entered because this field is not mandatory.

<textarea cols="40" rows="6" name="notes" id="notes" class="validated"

maxlength="1000"></textarea>

This means that the field will appear green when the screen first loads because even an empty value is valid.

Note

The textarea element does not support the pattern attribute. This means there is no straightforward way to ensure a textarea contains a minimum quantity of text.

You do not need to add any information to the last contacted field. This field is not mandatory, and Chrome has provided an input mask to ensure that the user cannot enter an invalid date.

Customizing Validation

The browser itself has generated all the validation messages that have been displayed up until this point. This brings some benefits; for instance, the messages are automatically localized based on the user's location and operating system settings.

If you look at the error that is generated when the contact name is less than five characters, however, it will appear as in the example in Figure 8.3.

image

Figure 8.3

This does not tell the user what the pattern should be; therefore, it is unlikely they would know how to resolve the issue.

It is possible to control the validation messages displayed to users, but unfortunately it is not as straightforward as you might expect and needs to be accomplished with JavaScript.

Note

The next example contains relatively simple JavaScript. You may, however, decide to return to this example after reading Lesson 11.

In order to customize the contact name message, add the following immediately before the closing html tag.

<script>

var contactName = document.getElementById('contactName')

contactName.oninvalid = function(e) {

e.target.setCustomValidity("");

if (!e.target.validity.valid) {

if (e.target.value.length == 0) {

e.target.setCustomValidity("Contact name is required.");

} else if (e.target.value.length < 5) {

e.target.setCustomValidity("Contact name must be at least 5 characters.");

}

}

};

</script>

Note

This needs to be placed at the bottom of the page because it attempts to access the contactName field when it executes. If it were added to the head tag the field would not have been present when this code executed. Although placing JavaScript at the end of the page is an acceptable solution to this problem, you will look at a more elegant solution later in the book.

If you enter four characters in the field, it should now display the message you have specified (see Figure 8.4).

image

Figure 8.4

In this code, you add an event listener to the contactName field, after retrieving it with the native DOM API. You then request that the browser sends you an event every time its validity status changes. When you receive that event, you first determine whether the field is invalid by accessing property on the field itself.

If the field is invalid, you can determine the current value of the field, and therefore determine which of the validation rules has been breached and create the appropriate message.

Once you determine the message you want to display to the user, you can call the setCustomValidity function on the field to set this value.

Disabling Validation

HTML5 provides a number of additional attributes for controlling validation.

A novalidate attribute can be added to the form in order to disable validation. If this is added, fields are still marked as valid and invalid, so the CSS styling you added to the web page will still work, but error messages will not be displayed to the user, and it is possible for the user to submit the web page, even if it is invalid.

Because HTML5 validation is enabled by default, this option is sometimes useful. For instance, any time a field is marked as type email, validation will be automatically added, even if you did not want it.

It is also possible to mark individual fields with the attribute formnovalidate to disable validation. It is common to add this attribute dynamically to fields when specific circumstances are met: For instance, some fields do not need to be validated if specific data is entered elsewhere in the form. This is a form of cross-field validation.

This can also be used to disable the default validation on a field—for instance, to allow an email field to contain an invalid email address.

Try It

In this Try It, you will add validation to the form you created in the Try It for Lesson 6. You can download this from the book's website or use the version you created in Lesson 6.

The book's website contains a completed version of this exercise under the name tryit.html. You can also view the screencast if you need additional help.

Lesson Requirements

You will need the tryit.html from Lesson 6, a text editor, and a browser.

Step-by-Step

1. Open the tryit.html file in your text editor.

2. Add attributes to the fullName field so that it is mandatory for the user to enter a value, and the minimum length of 7 characters, and a maximum length of 50 characters.

3. For the notes field, make the field mandatory and add a pattern that ensures the field contains no more than 500 characters of text.

4. Change the salary field to define a minimum salary of $20,000, and a maximum salary of $200,000. Although this was not shown in the lesson, it can be achieved with the min and max attributes, but make sure not to include commas or the dollar sign in the numbers.

5. Add a style to the web page so that any invalid input field or textarea displays with a red border. Although it may not seem like it, the line around an input field or textarea is just a simple border and can therefore be modified with CSS.

The finished version of the form should display as you see in Figure 8.5 when a validation error occurs.

image

Figure 8.5

Reference

Please select the video for Lesson 8 online at www.wrox.com/go/html5jsjquery24hr. You will also be able to download the code and resources for this lesson from the website.