You gotta love HTML5’s input types and patterns

While working on updates of the admin-screen of Autoptimize, I wanted some checks on the URL a user can enter for a CDN. At first I thought I’d do some jQuery-based validation but then I came accross a page (on StackOverflow I guess) that mentioned the new input types and the use of validation patterns, so now I just have this beauty in place;

<input type="url" pattern="^(https?:)?\/\/([\da-z\.-]+)\.([\da-z\.]{2,6})([\/\w \.-]*)*\/?$" />

And to make sure the user gets a visual indication if the string isn’t a valid URL (according to the regex) there’s this CSS oneliner:

input[type=url]:invalid {color: red; border-color:red;}

The nice thing about this is that it is pretty backwards compatible;

  1. browsers that do not know type=”url” will just consider it type=”text” and can still enforce the pattern (if supported).
  2. browsers who support type=”url” but not the pattern, will do more basic validation.

And for browsers that do not support type=”url” nor patterns, there are multiple polyfills available that force older browsers to comply as well. But who cares about older browsers, right?

2 thoughts on “You gotta love HTML5’s input types and patterns

  1. Andy Goossens

    The pattern won’t work for IDN though.
    And with {2,6} it looks like you want to restrict the TLD length too much. Forgot about “.vlaanderen”? :-)

    Reply
    1. frank Post author

      But regexes aren’t supposed to be read Andy!

      No, seriously; guess those (and esp. IDN) are some of the reason why the default pattern for URL is that simple (“a:” suffices to pass).

      Hoping there’s no CDN’s on .vlaanderen though ;-)

      Reply

Leave a Reply

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