HTML5 Input Patterns and Invalid Regex

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!

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate for Extend by Auth0. He focuses on serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA