HTML and CSS Reference
In-Depth Information
3.12 Restricting Values
Problem
You want to restrict the value of an input field according to a set of rules you specify.
Solution
Use the HTML5 pattern attribute to specify a regular expression that will be used to
validate the user's input:
<form>
<p><label>Telephone number <input type="tel" name="phone"
pattern="[2-9][0-9]{2}-[0-9]{3}-[0-9]{4}"
title="North American format: XXX-XXX-XXXX"></label></p>
<p><button type="submit">Submit</button></p>
</form>
Discussion
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
Mastering Regular Expressions , by Jeffrey Friedl. Instead, the Regular
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 .
Regular expressions for pattern must use the same syntax as in JavaScript. Keep in
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 .
 
Search WWH ::




Custom Search