Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 239
Arslan Sohail Avatar asked Jun 19 '15 06:06

Arslan Sohail


People also ask

How do I check if a URL is valid in node JS?

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.

How do you check if a URL is valid?

You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.

How do you use a valid URL?

Valid URL must begin with a scheme name, e.g. https:// . URL is working starting from Edge so everything below it might not work as you expect. Make sure you check the compatibility first. – Tony T.

How do I validate node JS?

js file inside the helper folder as seen below: const Validator = require('validatorjs'); const validator = async (body, rules, customMessages, callback) => { const validation = new Validator(body, rules, customMessages); validation. passes(() => callback(null, true)); validation. fails(() => callback(validation.


1 Answers

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

like image 112
Jossef Harush Kadouri Avatar answered Oct 19 '22 04:10

Jossef Harush Kadouri