This is just a quick note to discuss something interesting a reader and I encountered last week. As you know (hopefully!), the input tag supports a pattern argument. The value of the pattern argument is a regular expression that is compared against the value of the input field. This allows for custom types of validation for data not covered by the host of new field types added in HTML5.
But here's an interesting question. What exactly happens when you supply a bad regular expression? As you might expect - absolutely nothing. A reader on my blog noticed that a pattern value he had used was letting everything pass and not validating as he expected. When this happens, nothing will show up in the console and you really don't have a good idea as to what is going on.
Luckily there is a way to check for this. First - note that the Mozilla Dev Network docs on Input say this about pattern:"The regular expression language is the same as JavaScript's." This is probably obvious, but when it comes to browsers, I try not to assume anything. But armed with this knowledge you have a simple way to double check your patterns before using them in an input field.
I opened up my console, took his regex, and simply put it in a new RegExp object. The second I pasted in his bad regex, I got an error. Here is an example:
Something to keep in mind, folks!
Archived Comments
Brackets has an Inline Regex Editor extension that can also help with this.
An update: In Firefox, as soon as you type into the field, you get this:
SyntaxError: invalid range in character class
in the console. It isn't terribly obvious to me, but, it is *something* at least. I double checked Chrome - no message. I also checked Safari, but apparently Safari isn't working with validation at all. CanIUse says (http://caniuse.com/#feat=fo... that it should do something on blur (my reading of the note) but I couldn't see any validation.
Randy: I just tried Peter's extension - that's pretty darn slick.
The spec says the following about the `pattern` attribute: http://www.whatwg.org/specs...
Note: This implies that the regular expression language used for this attribute is the same as that used in JavaScript, except that the pattern attribute is matched against the entire value, not just any subset (somewhat as if it implied a `^(?:` at the start of the pattern and a `)$` at the end).
So, to properly test the regular expression in JavaScript before using it as a `pattern` attribute value, prepend `^(?:` and append `)$` to the regex.
Good reminder there, Mathias, thank you.