{

How to validate URL and domain in Nodejs with examples


How to validate  URL and domain in Nodejs with examples

It is a short tutorial on how to validate the below things in Nodejs Application.

  • validate URI
  • domain name validation

validation on URI is to check valid URL or not and Domain validation is to check URL contains HTTP or HTTPS and extension is present

How to check Domain URL validation with HTTP or HTTPS in nodejs

Sometimes, We want to check abc.com is a valid URL or not

nodejs provides valid-url npm package to validate

Install node valid-url package in application with below command

npm i valid-url

Here is a code for nodejs URL validation

var urlmodule = require(‘valid-url’);

var url = "https://google.com"
    console.log(urlmodule.isUri(url));  //https://google.com
    console.log(urlmodule.isHttpUri(url)); // undefined
    console.log(urlmodule.isHttpsUri(url)); //https://google.com
    console.log(urlmodule.isWebUri(url));//https://google.com

valid-url package provides following methods

  • isUri - checks for valid uri and returns same if valid,else undefined
  • isHttpUri - checks for http url, returns url if url is http,else return undefined
  • isHttpsUri - checks for https url, returns url if url is https,else return undefined
  • isWebUri - Checks for valid http or https url

How to check URL is valid in Nodejs?

Another way is using the url-exists package in nodejs

first, install using the below command

npm install --save url-exists

Here are steps to execute in nodejs with a callback of checking URL validation.

const urlExists = require("url-exists");

urlExists(url, function(err, exists) {
  if (exists) {
    console.log('Valid URL');
  } else {
    console.log('Not valid URL');
  }
});

regular expression to check valid URL or not

In javascript, Regular expressions check a string against a pattern of expression.

Here is an example to check

const url="google.com"
  var regexpression = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;

  console.log(regxpression.test(url)); // true
        if (regexpression.test(url)) {
            console.log("Url is valid");
        } else{
            console.log("Url is not valid!");
    }

Conclusion

In this tutorial, You learned how to validate URL and domain validation in nodejs using npm libraries and regular expression.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.