Validating a URL in Node.js

后端 未结 4 1424
我在风中等你
我在风中等你 2020-12-24 08:53

I want to validate a URL of the types:

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

相关标签:
4条回答
  • 2020-12-24 08:56

    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');
      }
    });
    
    0 讨论(0)
  • 2020-12-24 09:04

    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

    0 讨论(0)
  • 2020-12-24 09:19

    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;
        }
    };
    
    0 讨论(0)
  • 2020-12-24 09:21

    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.

    0 讨论(0)
提交回复
热议问题