Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 2: Form validation CHAPTER 7 325


with validation at the browser is that browser validation is easy for an attacker to bypass.
Therefore, you must provide server-side validation for security and client-side validation to
minimize the time users must wait to find out that there is an input error. This lesson discusses
client-side validation that is available in HTML5.

After this lesson, you will be able to:
■■Understand HTML5 form validation.
■■Apply HTML5 form validation.

Estimated lesson time: 20 minutes

Required validation


Probably the simplest type of form validation is the required attribute on most form submis-
sion elements. The required attribute is a Boolean attribute that requires the user to enter
data before submitting to the server. Consider the following form.
<form id="myForm">
Favorite Car:
<select name="favoriteCar" required="required">
<option>Ford Fiesta</option>
<option value="Chevy">Chevrolet</option>
<option>BMW</option>
</select><br />
Comment:
<input type="text" name="comment" required="required"/><br />
Email:
<input type="email" name="email" required="required"/><br />
<button type="submit" name="submit">Submit</button>
</form>

In this form, all the form submission elements have required attributes. When the page
is displayed, there is no indication of required fields. If the user immediately clicks the
Submit button, the browser cancels the submission, and the result is displayed, as shown
in Figure 7-5. The <select> element doesn’t have the red border because the first option is
selected by default.
Browsers display validation errors differently. For example, the message in Chrome and
Firefox is, “Please fill out this field,” and the message in Chrome is prefixed with an icon.
Opera and Internet Explorer have the same message, “This is a required field,” but instead of
a red border, the background of the message is red. You can provide CSS styles rules to suit
your needs.
Free download pdf