HTML and CSS Reference
In-Depth Information
The specifi cation 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 going to already be 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 fi nd 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 fi ve,
with an optional suffix of a dash then another sequence of
four numbers.
We could extend this match to also validate UK post codes
(using a simplifi ed post code match), by making the pattern
more complicated:
<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”>
Now our regular expression has become much more compli-
cated and it can be quite tricky to test in the pattern. Since the
pattern's regular expression matches the syntax of a JavaScript
regular expression, we can test this in a browser console such
as Firebug or Opera Dragonfl y, using pure JavaScript to test
whether the pattern is going to work. In the example below, I'm
just testing the UK post code match, and using the JavaScript
test method to experiment. Note that I've also wrapped my tests
with the leading ^(:? and trailing )$ as the HTML5 spec states:
/^(:?[a-zA-Z]{1,2}\d{1,2}\s?\d[a-zA-Z]{1,2})$/.test
¬ (“bn14 8px”)
> true
/^(:?[a-zA-Z]{1,2}\d{1,2}\s?\d[a-zA-Z]{1,2})$/.test
¬ (“bn149 8px”)
> false
 
Search WWH ::




Custom Search