Nodejs URL and domain validation with examples


This is an short tutorial on how to validate 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 presnt

How check Domain url validation with http or https in nodejs

Some times, We want to check abc.com is 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 an 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 url-exists package in nodejs

first install using below command

npm install --save url-exists

Here are steps to execute in nodejs with 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, Regualr expressions are used to 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.