简体   繁体   中英

Validating a URL in Node.js

I want to validate a URL of the types:

  • www.google.com
  • http://www.google.com
  • google.com

using a single regular expression, is it achievable? If so, kindly share a solution in JavaScript.

Please note I only expect the underlying protocols to be HTTP or HTTPS. Moreover, 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 the user matches any of the above listed three cases, it should return true on the other hand if it doesn't it should return false .

There's a package called valid-url

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 want a simple REGEX - check this out

There is no need to use a third party library .

To check if a string is a valid URL

  const URL = require("url").URL;

  const stringIsAValidUrl = (s) => {
    try {
      new URL(s);
      return true;
    } catch (err) {
      return false;
    }
  };

  stringIsAValidUrl("https://www.example.com:777/a/b?c=d&e=f#g"); //true
  stringIsAValidUrl("invalid"): //false

Edit

If you need to restrict the protocol to a range of protocols you can do something like this

const { URL, parse } = require('url');

const stringIsAValidUrl = (s, protocols) => {
    try {
        new URL(s);
        const parsed = parse(s);
        return protocols
            ? parsed.protocol
                ? protocols.map(x => `${x.toLowerCase()}:`).includes(parsed.protocol)
                : false
            : true;
    } catch (err) {
        return false;
    }
};

stringIsAValidUrl('abc://www.example.com:777/a/b?c=d&e=f#g', ['http', 'https']); // false
stringIsAValidUrl('abc://www.example.com:777/a/b?c=d&e=f#g'); // true

Edit

Due to parse depreciation the code is simplified a little bit more. To address protocol only test returns true issue, I have to say this utility function is a template. You can adopt it to your use case easily. The above mentioned issue is covered by a simple test of url.host !== ""

const { URL } = require('url');

const stringIsAValidUrl = (s, protocols) => {
    try {
        url = new URL(s);
        return protocols
            ? url.protocol
                ? protocols.map(x => `${x.toLowerCase()}:`).includes(url.protocol)
                : false
            : true;
    } catch (err) {
        return false;
    }
};

The "valid-url" npm package did not work for me. It returned valid, for an invalid url. What worked for me was "url-exists"

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

urlExists(myurl, function(err, exists) {
  if (exists) {
    res.send('Good URL');
  } else {
    res.send('Bad URL');
  }
});

Using the url module seems to do the trick.

Node.js v15.8.0 Documentation - url module

const url = require('url');    

try {
  const myURL = new URL(imageUrl);
} catch (error) {
  console.log(`${Date().toString()}: ${error.input} is not a valid url`);
  return res.status(400).send(`${error.input} is not a valid url`);
}

I am currently having the same problem, and Pouya's answer will do the job just fine. The only reason I won't be using it is because I am already using the NPM package validate.js and it can handle URLs .

As you can see from the document, the URL validator the regular expression based on this gist so you can use it without uing the whole package.

I am not a big fan of Regular Expressions, but if you are looking for one, it is better to go with a RegEx used in popular packages.

Other easy way is use Node.JS DNS module.

The DNS module provides a way of performing name resolutions, and with it you can verify if the url is valid or not.

const dns = require('dns');
const url = require('url'); 

const lookupUrl = "https://stackoverflow.com";
const parsedLookupUrl = url.parse(lookupUrl);

dns.lookup(parsedLookupUrl.protocol ? parsedLookupUrl.host 
           : parsedLookupUrl.path, (error,address,family)=>{
   
              console.log(error || !address ? lookupUrl + ' is an invalid url!' 
                           : lookupUrl + ' is a valid url: ' + ' at ' + address);
    
              }
);

That way you can check if the url is valid and if it exists

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM