This is an excerpt from the HTML5 Solutions: Essential Techniques for HTML5 Developers book by Apress (where I'm one of the author).
Solution 4-8: Creating custom input types using regular expressions
Regular expressions provide a powerful, concise, and flexible means for matching strings of text, such as
particular characters, words, or patterns of characters. A regular expression is written in a formal language
that can be interpreted by a regular expression processor, which is a program that either serves as a
parser generator or examines text and identifies parts that match the provided specification. See Wikipedia
for more information: http://en.wikipedia.org/wiki/Regular_expression.
HTML5 allows you to check the user’s inputs and to match the input values against a regular expression.
What’s involved
The code that you needed to write to use regular expressions with previous versions of HTML was
as follows:
<input type="text" name="ssn"
onblur="if (!^\d{3}-\d{2}-\d{4}$this.value) alert(this.title+'\nAn error occurred. Please
verify your data.');" title="The Social Security Number"/>
On the onblur event of the input element, a JavaScript statement is executed. It controls the pattern to be
applied to the data in the field, and it provides an error message if the validation wasn’t successful.
With HTML5, a new attribute is available that allows you to associate a pattern of characters via regular
expressions to a text input to be applied as validation of the data inserted in the field. The markup for this
is really simple:
<input type="text" name="ssn" pattern="(!^\d{3}-\d{2}-\d{4}$"
The value specified in the pattern attribute must match the JavaScript pattern production as described in
this document: www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf.
Continue reading "Creating custom HTML5 input types using regular expressions" »