HTML and CSS Reference
In-Depth Information
Suppose you wish to accept the user's first name. A name can contain only the letters A to Z in
uppercase or lowercase. The HTML5 <input> element provides a pattern attribute that takes any valid
regular expression and validates an inputted value against it. If the inputted value doesn't match the
pattern specified by the regular expression, an error is shown. The following line of markup shows how to
use the pattern attribute:
<input id="irstName" type="text" name="irstName" pattern="^\s*([a-zA-Z]+)\s*$"
required="required" />
The pattern attribute of this <input> tag is set to a regular expression that allows only alphabetic
characters in the text box. If you try to enter a number as a first name, you get an error, as shown in Figure
5-12.
Figure 5-12. Validating data using the pattern attribute
Entering numeric data in the input field generates an error because the regular expression allows only
alphabetic characters. The default error message leaves the user clueless about what exact format is
expected or what went wrong; later, you learn to customize the error message displayed by the browser.
Turning HTML5 Validations On and Off
When you use the new input types and related validation techniques, your form is validated before it's
submitted to the server. However, at times you may want to skip the form validation altogether. During the
testing phase, you may want to test your server-side validations, and you may want to disable HTML5
validations temporarily. In certain cases, it might be all right to submit a form without performing any
validations. For example, let's say you have a Cancel button or a Help button on a form. Because actions
indicated by these buttons don't rely on the data, you can safely bypass the validations.
You can turn off the HTML5 validations at two distinct places:
• At the <form> tag level
• At the Submit button level
The former approach is good during the testing phase, and the latter approach is suitable for cases
where a form needs to be submitted regardless of the control values.
To turn off the validations at the form level, HTML5 offers the novalidate attribute. At the Submit
button level, the HTML5 formnovalidate attribute does the job. The following fragment of markup shows
how to use both of these attributes:
<form id="form1" method="post" novalidate="novalidate"></form>
<input type="submit" formnovalidate="formnovalidate" />
 
Search WWH ::




Custom Search