HTML and CSS Reference
Sometimes developers have no other option besides writing the same boilerplate code over and over
again, no matter how annoying it is. A good example of boilerplate code that it would be great to
stop writing is validation of input forms in HTML pages. Any data collected from an HTML input form
should be carefully validated on the server before being used for some business tasks. However, some
basic validation tasks can be easily delegated to the browser and commanded by the developers
HTML5 helps reduce the amount of boilerplate code requested to build effective input forms. I've
already mentioned the newest attributes of the HTML5 <input> element; the next step is to take a
look at other attributes you can leverage to control the whole process of form submission, including
ways to ensure that the user has not left required fields blank, and that the user input matches
expected patterns. For example, if you ask for a phone number, the user shouldn't be allowed to enter
something that couldn't possibly be a valid phone number.
Detecting required fields
By adding the required attribute to a <input> element, you tell the browser that the input field cannot
be blank when the form that contains the input element is submitted. You use the required attribute
only if the field is not considered optional.
Consider the following content of an HTML page named required.html :
<input type="text" placeholder="Your PIN" required />
<input type="submit" value="Enter" />
When the user pushes the submit button and the text field is empty, the browser automatically
denies the post and displays an error message. The specific content, form, and shape of the error
message may change according to the browser; the overall behavior, though, is similar on all HTML5-
compliant browsers. Figure 2-9 shows how Internet Explorer 10 deals with required fields left empty.
FIGURE 2-9 The required attribute in action.