How to Validate URL in JavaScript

Anika Tabassum Era Feb 15, 2024
  1. Use JavaScript URL Constructor to Validate URL
  2. Use Anchor Tag to Validate a String As URL in JavaScript
  3. Use Regex to Match URL Pattern and Validate URL in JavaScript
How to Validate URL in JavaScript

In JavaScript, you get a number convention to validate a URL. If we dissect a URL, we get a protocol, hostname, domain-name, paths of single or multiple stages.

We will use the JavaScript URL constructor to take the given string. After that, we will pass our string to an anchor tag and see how this method reacts.

The most common way to match string and URL is to perform a regex test().

Use JavaScript URL Constructor to Validate URL

The JavaScript URL constructor and its way of accepting strings focus on the basic URL pattern- a protocol, hostname, domain name, etc.

We will initiate a try-catch scope for the following example and let the try scope check if the string follows the basic URL pattern. Else, we will consider the string a failure and proceed further.

Code Snippet:

function isValidHttpUrl(string) {
  var url;
  try {
    url = new URL(string);
  } catch (err) {
    return false;
  }
  return url.protocol === 'http:' || url.protocol === 'https:';
}
console.log(isValidHttpUrl('file:///Y:/bleh/index.html'));
console.log(isValidHttpUrl('https://www.youtube.com/watch?v=iFP-EWO_Q_o'));
console.log(isValidHttpUrl('en.wikipedia.org'));

Output:

Use JavaScript URL Constructor to Validate URL

The demonstration clearly explains that even if the last URL results in the wikipedia.org in a browser, our function isValidHttpUrl will show false. It doesn’t have a prior protocol, and such a pattern is not considered a URL.

Use Anchor Tag to Validate a String As URL in JavaScript

An anchor tag is followed by a href (header reference). Whenever we create such an element and try to manipulate the DOM, we will set the string to a.href.

Consequently, a hostname with a missing protocol will be attached. Let’s check the instance for a clear view.

Code Snippet:

function isValidURL(str) {
  var a = document.createElement('a');
  a.href = str;
  return a.protocol === 'http:' || a.protocol === 'https:';
}
console.log(isValidURL('file:///Y:/bleh/index.html'));
console.log(isValidURL('https://www.youtube.com/watch?v=iFP-EWO_Q_o'));
console.log(isValidURL('en.wikipedia.org'));

Output:

Use Anchor Tag to Validate a String as URL

The function isValidURL takes the string, and as soon as it is passed to the a.href, it gains the protocol.

It doesn’t care to work on the string if it does not follow a URL pattern, and this condition will consider the string a failure and return it as false.

Use Regex to Match URL Pattern and Validate URL in JavaScript

The test() method of regex matches outputs in the Boolean form. As we generate a regex for checking the string if it is a URL, it will only result in true or false.

Code Snippet:

function isValidUrl(string) {
  const pattern =
      /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm;
  return pattern.test(string);
}
console.log(isValidUrl('file:///Y:/bleh/index.html'));
console.log(isValidUrl('https://www.youtube.com/watch?v=iFP-EWO_Q_o'));
console.log(isValidUrl('en.wikipedia.org'));

Output:

Use Regex to Match URL Pattern and Validate URL

The instance here has a specific regex pattern, and according to that, there is an explicit mention of the protocol. That is why our third-string, en.wikipedia.org, shows the result as false.

However, our third case would have been satisfying if we had generated the regex differently, where the protocol portion was optional.

Anika Tabassum Era avatar Anika Tabassum Era avatar

Era is an observer who loves cracking the ambiguos barriers. An AI enthusiast to help others with the drive and develop a stronger community.

LinkedIn Facebook

Related Article - JavaScript String