HTML and CSS Reference
In-Depth Information
The pattern attribute
Some of the input types mentioned previously—email, number,
url, and so on—are really “baked-in” regular expressions, as the
browser just checks if the values entered look like they should.
Suppose you want to match against a different template? The
pattern attribute allows you to specify a custom regular expres-
sion that the input must match. So, if the user must always enter
a single digit plus three uppercase alphabetic characters, the
regular expression would be one number [0-9] and three letters
[A-Z]{3}, all in uppercase, and the input would be coded
<input pattern=”[0-9][A-Z]{3}” name=part
¬ title=”A part number is a digit followed by three
¬ uppercase letters.”>
Yo u c o u l d a l s o a d d a placeholder=”1ABC” or something similar
as a short hint.
The specification explains that the regular expressions in the
pattern attribute match the syntax of regular expressions in
JavaScript, except that there's an implied ^(:? at the beginning
and )$ at the end.
So if you're accustomed to working with regular expressions,
you're already familiar with what you need to do. If not, you've
got the fun world of regular expressions to explore!
The Internet is littered with JavaScript regular expressions that
match this, that, and the other, so it's likely that you'll find what
you're looking for. However, regular expressions, when kept
simple, are relatively easy to get working.
For example, to match a ZIP code in the format of 99999 or
99999-9999 (assuming the 9s are all kinds of numbers), you
can use:
<input pattern=”[0-9]{5}(\-[0-9]{4})?” title=”A zip code in
¬ the format of 99999 or 99999-9999”>
This regular expression looks for a numerical sequence of five,
with an optional suffix of a dash followed by another sequence
of four numbers.
We could extend this pattern to also validate UK post codes
(using a simplified post code match):
<input required pattern=”[0-9]{5}(\-[0-9]{4})?|[a-zA-Z]
¬ {1,2}\d{1,2}\s?\d[a-zA-Z]{1,2}” name=part title=”A valid
¬ zip code or UK postcode”>
NoTE If regular
expressions scare you
but you want to learn more, or
you're keen to fuel your regular
expression ninja skills, take a
gander at Steven Levithan's blog
( http://blog.stevenlevithan.com )
which talks about them almost
exclusively.
 
Search WWH ::




Custom Search