Validate URL form field in Javascript Without Regular Expression

Use-Cases of this Tutorial

  • Instead of using a complex regular expression to validate a URL form field, you're looking for a browser-based HTML5 solution.

Validating a HTML form in Javascript is almost the part of every web application. In most of the cases, we tend to use regular expressions for validation. In the case of a URL, finding a regular expression that validates every type of URL possible is very difficult. Even more if you manage to find one, the regular expression will be highly complex.

Why do all this when the browser is providing a HTML <input> element of type url ? Just use <input type="url" /> in your HTML and check validation in Javascript with checkValidity() method. No regex needed !

Implementation and Validation

Below is the HTML markup. On click of the button, form will get validated.

<form novalidate> <input type="url" required id="form-url" /> </form> <button id="validate-field">Validate</button>

There are 3 important things to note :

  1. The URL input type should have a parent <form> element
  2. The <form> element should have a novalidate attribute to indicate that the form is not to be validated on submit (You don't the browser default behaviour, you want to validate it yourself)
  3. The <input> element should have a required attribute to indicate that this field is required

On the Javascript / jQuery side, use checkValidity method to validate the URL input type.

$("#validate-field").on('click', function() { /* document.getElementById("form-url") */ if($("#form-url").get(0).checkValidity() == true) { /* all good */ } else { /* validation error in URL */ } });

$("#form-url").get(0) in jQuery is document.getElementById("form-url") in pure Javascript.

Advantages of Using <input type="url" />

By using a URL input type, you can validate any legal URL, however complex it might be. Legal URLs include :

  • Valid URLs as defined in RFC 3986 and 3987
  • URLs can have UTF-8 and UTF-16 characters as well. For example a URL with Korean characters위키백과:대문, or a URL with Arabic characters برباتوففيالنادي

Do NOT Forget Server-Side Validation

Regardless of the fact that you're doing client side validation with Javascript, do not forget to validate form fields on the server as well (with PHP or something). Also do not forget to escape special characters while inserting form data into your database with the help of database functions (real_escape_string() in case of PHP-MySql). The real need of validating form fields is on the server side, only that can make your application secure.