Extending HTML5 input types with regular expressions

I was reading Jeremy Keith’s, HTML5 for Web Designers which I’ve written about before. This quote is from the section on new <input> tag types, end of chapter 4:

The good news is that you can use the pattern attribute to specify exactly what kind of value is expected. The bad news is that you have to use a regular expression:


<label for="zip">US Zip code</label>
<input id="zip" name="zip" pattern="[d]{5}(-[d]{5})">US Zip code</label>

Most of the time, you’ll never need to use the pattern attribute. On the occasions that you do, you have my sympathy.

Although I’m appreciative of Keith’s lucid explanation, I find that I disagree with him on this point. It’s a great step that we can define input types at will; but it’s even better that the patterns are defined using regular expressions. I can’t think of a more succinct and powerful way to allow infinite extensibility.

As a side note, the example in the book will match 9-digit zip codes, but unfortunately allows other strings also (such as “asdf12345-2345″ or “12345-2345qwer”). I think the following example might be more useful for validating zip codes.


<input id="zip" name="zip" pattern="^[d]{5}(-[d]{4})?$">

The regular expression here matches either 5- or 9-digit strings and nothing else. Unfortunately, you can’t test this in a browser, since no browsers seem to support this attribute yet (I tested Chrome, Safari, Firefox). When browsers do support it, if they end up using regex parsing similar to javascript, you’d be set.

Update November 2011: I’ve come back and tested this and found that the original example does in fact limit to only 9-digit zip codes. Some regex parsers (perl, php and javascript, for example) would have matched “asdf12345-1234″ as matching the book’s regex. It seems that the browser parsers (I checked Firefox and Chrome) are a little more strict by default and don’t require you to indicate the start and end of the string with ^ and $, respectively. However, the regex I included does have the feature of accepting either 5-digit or 9-digit zip codes. So if that’s what you’re looking for, have at it!

PS. Sorry Jeremy for saying your pattern was not strict enough the first time round.

One thought on “Extending HTML5 input types with regular expressions

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>