How to validate URL address in JavaScript?


In this tutorial, let us discuss how to validate URL addresses in JavaScript.

A URL or Uniform Resource Locator identifies web pages, images, and videos on the internet. URLs are website addresses that transfer files, send emails, and many more.

URLs consist of a protocol, domain name, and so on. URL indicates how the browser gets the data and where to get the data.

We use a URL in the anchor tags or buttons to navigate the user to another location. We must verify the URL's validity before using it.

URL Rule

  • URL must start with http:// or https://.

  • URL may or may not contain www.

  • URL must not be a Magnet URL or Torrent URL.

Now, let us see the methods to validate a URL address.

Using Regular Expressions

A regular expression describes a pattern of characters. We use these patterns to match some text.

Users can follow the syntax below to use this method.

Syntax

string.match(regExp);
var pattern = new RegExp(regExp);
pattern.test(string);

The first syntax matches a regular expression. The second syntax tests for a URL pattern.

Parameters

  • string − string is the URL to validate.

  • regExp − The regular expression to match a URL.

  • pattern − The regular expression pattern to test a URL.

Example

This program shows multiple regular expressions and the regular expression pattern match validate the URL.

<html> <body> <h2> Validating the URL using <i> regular expressions </i> </h2> <div id = "urlValBtnWrap"> <button id = "urlValBtn"> Click Me </button> </div> <p id="urlValOut"></p> <script> var urlValBtnWrap = document.getElementById("urlValBtnWrap"); var urlValBtn = document.getElementById("urlValBtn"); var urlValOut = document.getElementById("urlValOut"); var urlRegStr = ""; urlValBtn.onclick = function(){ urlValBtnWrap.style.display = "none"; var regEx1 = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm; var url1 = 'https://www.test.com'; urlRegStr += url1 + ' is ' urlRegStr += regEx1.test(url1) + "<br><br>"; var regEx2 = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/; var url2 = 'http://www.test.com'; urlRegStr += url2 + ' is ' urlRegStr += regEx2.test(url2) + "<br><br>"; var url3 = 'www.test.com'; urlRegStr += url3 + ' is ' urlRegStr += regEx2.test(url3) + "<br><br>"; var regEx3 = /^((https?):\/\/)?([w|W]{3}\.)+[a-zA-Z0-9\-\.]{3,}\.[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/; var url4 = 'httpe://www.test.com'; urlRegStr += url4 + ' is ' urlRegStr += regEx3.test(url4) + "<br><br>"; var regEx4 = /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/g; var url5 = 'test'; urlRegStr += url5 + ' is ' urlRegStr += regEx4.test(url5) + "<br><br>"; var pattern = new RegExp('^(https?:\/\/)?'+ //protocol '((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ //domain '((\d{1,3}\.){3}\d{1,3}))'+ //IP address '(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ //port and path '(\?[;&a-z\d%_.~+=-]*)?'+ // query string '(\#[-a-z\d_]*)?$','i'); // fragment locator urlRegStr += "<b>new RegExp</b><br><br>"; var str1 = 'http:test'; urlRegStr += str1 + ' is ' urlRegStr += pattern.test(str1) + "<br><br>"; urlValOut.innerHTML = urlRegStr; }; </script> </body> </html>

Using the URL() Constructor

The URL() constructor returns a newly created URL object. The constructor throws a TypeError if the base URL or resultant URL is invalid.

Users can follow the syntax below to use this method.

Syntax

var url = new URL(urlStr);
new URL(url, base);
return url.protocol === 'http:' || url.protocol === 'https:';

The first two syntaxes create a new URL, either with a base or without a base. The second syntax is to check the URL protocol validity.

Parameters

  • url − URL is a string that represents an absolute or relative URL. A base is a must for a relative URL. The constructor ignores the base in the case of an absolute URL.

  • urlStr − The string to create a URL.

  • base − base is an optional string parameter. The default value is undefined.

Example

In this program, the URL method validates the URLs and returns a type error in the case of invalid URLs.

<html> <body> <h2>Illustrating the valid and invalid URLs with <i>URL method</i></h2> <div id="urlValBtnWrap"> <button id="urlValBtn">Click Me</button> </div> <p id="urlValOut"></p> <script> var urlValBtnWrap = document.getElementById("urlValBtnWrap"); var urlValBtn = document.getElementById("urlValBtn"); var urlValOut = document.getElementById("urlValOut"); var urlStr = ""; urlValBtn.onclick = function(){ urlValBtnWrap.style.display = "none"; let str1 = 'https://teach.tuitor.com'; let url1 = new URL("/", str1); let url2 = new URL(str1); urlStr += "<b>Valid Urls</b><br><br>"; urlStr += "<b>Base</b> " + str1 + "<br><br>"; urlStr += "Url " + url1 + "<br><br>"; urlStr += "Url " + url2 + "<br><br>"; let url6 = new URL('/sub1/sub2', url1); urlStr += "<b>Base</b> " + url1 + "<br><br>"; urlStr += "Url " + url6 + "<br><br>"; let url3 = new URL('/sub1/sub2', url2); urlStr += "<b>Base</b> " + url2 + "<br><br>"; urlStr += "Url " + url3 + "<br><br>"; let url4 = new URL('sub1/sub2', url2); urlStr += "Url " + url4 + "<br><br>"; let url9 = new URL('http://www.test.com', url2); urlStr += "Url " + url9 + "<br><br>"; let url5 = new URL('/sub1/sub2', url3); urlStr += "<b>Base</b> " + url3 + "<br><br>"; urlStr += "Url " + url5 + "<br><br>"; let url7 = new URL('/sub1/sub2', "https://teach.tuitor.com/fr-FR/toto"); urlStr += "<b>Base</b> " + "Nothing" + "<br><br>"; urlStr += "Url " + url7 + "<br><br>"; let url8 = new URL('http://www.test.com', ); urlStr += "<b>Base</b> " + "Empty String" + "<br><br>"; urlStr += "Url " + url8 + "<br><br>"; let url10 = new URL("", "https://test.com/?query=1") urlStr += "Url " + url10 + "<br><br>"; //removes query arguments) let url11 = new URL("/a", "https://test.com/?query=1") urlStr += "Url " + url11 + "<br><br>"; //relative URLs let url12 = new URL("//test.com", "https://test.com") urlStr += "Url " + url12 + "<br><br>"; //relative URLs urlStr += "<b>TypeError Cases</b><br><br>"; try{ url13 = new URL('/sub1/sub2', ''); //'' is not a valid URL new URL('/sub1/sub2'); //'/sub1/sub2' is not a valid URL } catch(e){ urlStr += e + "<br><br>"; } urlStr += "<b>Check Validity</b><br><br>"; urlStr += "https://code.dev.com is " + isValidUrl('https://code.dev.com') + "<br><br>"; urlStr += 'test://code.dev.com is ' + isValidUrl('test://code.dev.com') + "<br><br>"; urlStr += 'Code Dev is ' + isValidUrl('Code Dev'); urlValOut.innerHTML = urlStr; }; function isValidUrl(string) { try { var url = new URL(string); return url.protocol === 'http:' || url.protocol === 'https:'; } catch (err) { return false; } } </script> </body> </html>

This tutorial taught us two methods to validate a URL. The first method suggests using a regular expression match or a pattern test. The second method is the built-in URL method. The URL method is easy because we can avoid the test case missing in the case of regular expressions.

Updated on: 23-Nov-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements