Cartoon from xkcd #1171: Perl Problems
The pattern attribute enables the validation of the user's input on the fly (also at submission time), based on regular expressions. It applies to the text, search, url, tel, email, and password input types.
The pattern attribute follows the syntax of JavaScript regular expressions.
A must read: a good catalog of ready-to-go patterns is available at html5pattern.com, an excellent Web site that proposes plenty of JavaScript patterns for the pattern attribute of HTML5 forms. The left hand menu proposes categorized patterns for postal codes, dates, phones, etc.
Just add a pattern attribute with a value that is the JavaScript regular expression that must match the entire string entered in the field. Note that the empty string is valid by default (except if the required attribute is used - this makes empty fields invalid).
It's best practice to systematically add a title attribute with a value that indicates what constitutes a valid entry. More on this in the section of this course dedicated to form validation.
<input type="text" name="country_code"
pattern="[A-Za-z]{3}"
title="3 letter country code"
/>
Try this online example at JSBin.
With the previous example, until the value of the input field is equal to 3 alphabetic characters, the field is invalid.
As seen in the previous examples, we used some CSS pseudo classes for automatically setting the background-color of the input field as we type.
Complete source code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of the pattern attribute</title>
<style>
input:invalid {
background-color: lightPink;
}
input:valid {
background-color: lightGreen;
}
</style>
</head>
<body>
<label for="code">Please enter a 3 letter country code:</label>
<input type="text" name="country_code"
pattern="[A-Za-z]{3}"
title="3 letter country code"
id="code"/>
</body>
</html>
Try this example online.
Complete source code:
<!DOCTYPE html>
<html lang="en">
<head> <meta charset="utf-8">
<title>Example of use of new HTML5 input field attributes</title>
<style>
input:focus:invalid { background-color: lightPink;}
input:valid { background-color:lightGreen; }
input:required {border: 2px solid red; }
input:optional {border: 2px solid green; }
</style>
</head>
<body>
<p>Attributes used: placeholder (for displaying a ghost example value), pattern, required (empty = invalid)...
<p>
<label for="inputID">Enter a pseudo (6-12 characters): </label>
<input id="inputID" name="Name"
placeholder="Name"
pattern="\w{6,12}"
required
title="6-12 characters allowed please"
type="text" />
</body>
</html>
Source code extract:
<input
id="website"
name="url"
type="url"
placeholder="http://www.domain.com"
title="http, https or ftp allowed"
pattern="(http|https|ftp):\/\/[a-zA-Z0-9\-\.\/]*"
/>