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;
- browsers that do not know type=”url” will just consider it type=”text” and can still enforce the pattern (if supported).
- 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?