@JoseInSanJose

Using HTML5 validation to validate URLs

Recently I came across Raymond Camden’s blog post on how to use HTML5 form validation with pure JavaScript. I thought I would write the URL version. I know, I’m totally stealing his code.

Validate URL:


function isValidUrl(s) {
  var elm = document.createElement('input');
  elm.setAttribute('type', 'url');

  elm.value = s;
  return elm.validity.valid;
}


isValidUrl('http://www.thewaymultimedia.com/'); //true
isValidUrl('www.thewaymultimedia.com/'); // false
isValidUrl('thewaymultimedia'); //false

Sweet, that is pretty simple. Thanks Raymond. Make sure to read Raymond’s blog post, since that’s where I stole the code from. Here is the list of data types you can implement this method for:

  • color
  • date
  • datetime
  • datetime-local
  • email
  • month
  • number
  • range
  • search
  • tel
  • time
  • url
  • week

Of course, it will only work with modern browsers and not all types are supported across the different browser vendor.