Validating a Url in Node.js

Hi there i want to validate url of the types www.google.com or http://www.google.com or google.com using a single reguar expression,is it achievable,if so, kindly share solution in javascript. Please note i only expect the underlying protocols to be HTTP or HTTPS morover the main question on hand is how can we map all these three patterns using one single regex expression in Javascript it doesn't have to check whether the page is active or not,if the value entered by user matches any of the above listed three case it should return true on the other hand if it doesnt it should return fasle.

Checking if a URL is live

This is a bit of a hack, buy if i required to do so, this is how i would approach it:

1st step

Parse and extract the domain/ip from the given url

  • e.g. http://drive.google.com/0/23 ------> drive.google.com

this is how to do that in nodejs:

var url = require("url");
var result = url.parse('http://drive.google.com/0/23');
console.log(result.hostname);

2nd step

ping the extracted domain/ip - not all servers will respond to ICMP (PING) requests due to network configuration.

var ping = require ("net-ping");

var session = ping.createSession ();

session.pingHost (target, function (error, target) {
    if (error)
        console.log (target + ": " + error.toString ());
    else
        console.log (target + ": Alive");
});

3rd step

You can perform an HTTP GET request to that url and check the status code.

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage.
  }
})
  • it's a bit risky if this is a web-service (since you can trigger actions).
  • would be more complicated if the url requires authentication / redirection
  • check out the request package

There's a Package for that!

You can use the existing nodejs package called validUrl

usage:

var validUrl = require('valid-url');

var url = "http://bla.com"
if (validUrl.isUri(url)){
    console.log('Looks like an URI');
} 
else {
    console.log('Not a URI');
}

Installation:

npm install valid-url --save

If you still want a simple REGEX

google is your friend. check this out