HTML and CSS Reference
3.12 Restricting Values
You want to restrict the value of an input field according to a set of rules you specify.
Use the HTML5 pattern attribute to specify a regular expression that will be used to
validate the user's input:
<p><label>Telephone number <input type="tel" name="phone"
title="North American format: XXX-XXX-XXXX"></label></p>
For years, web professionals have been writing validation scripts to check user data
prior to form submissions—and most of us would likely say that we have hated it.
With HTML5, we have a method for checking form input that doesn't rely on Java-
Script: regular expressions .
Regular expressions are very powerful and fun to write, once you get
the hang of them. You don't need to pore over a big book like O'Reilly's
Expressions Cookbook (also from O'Reilly) will help you to figure out
how to define some common expressions. Then you'll be ready for that
big book in no time.
The HTML5 pattern attribute allows you to specify a regular expression for an input
field. On blur of the input field or on submit of the form (browser implementations
vary), the user's input will be validated against the pattern; if it does not match, an error
will be displayed and the form will not be submitted, as shown in Figure 3-26 .
mind that the pattern attribute must match the entire value, or else the user will see
the error message.
When the pattern attribute is used, you should also specify a title attribute to describe
the pattern. The user agent may display this text to the user as a tool tip or as an error
if the submitted value does not match the pattern, as shown in Figure 3-27 .