Validating a Url in Node.jsWhat is the best regular expression to check if a string is a valid URL?What is a good regular expression to match a URL?How to validate a url with lots of querystringsNode: Check if URL is safe to requestValidate decimal numbers in JavaScript - IsNumeric()How to validate an email address in JavaScript?Encode URL in JavaScript?Get the current URL with JavaScript?How do I debug Node.js applications?How do I get started with Node.jsWriting files in Node.jsHow do I pass command line arguments to a Node.js program?How to decide when to use Node.js?How to exit in Node.js

What is temperature on a quantum level?

TikZ Can I draw an arrow by specifying the initial point, direction, and length?

Why is the total number of hard disk sectors shown in fdisk not the same as theoretical calculation?

Pre-1968 YA science fiction novel: robot with black-and-white vision, later the robot could see in color

Why did my rum cake turn black?

CPU overheating in Ubuntu 18.04

Back to the nineties!

Is this floating-point optimization allowed?

When is pointing out a person's hypocrisy not considered to be a logical fallacy?

How can I legally visit the United States Minor Outlying Islands in the Pacific?

How do I write a romance that doesn't look obvious

Alternatives to using writing paper for writing practice

QGIS Linestring rendering curves between vertex

Does Google Maps take into account hills/inclines for route times?

Was the Ford Model T black because of the speed black paint dries?

How to repair a laptop's screen hinges?

Why did the Japanese attack the Aleutians at the same time as Midway?

About the number of real roots

Installing ubuntu with HD + SSD

Is purchasing foreign currency before going abroad a losing proposition?

What is the German equivalent of 干物女 (dried fish woman)?

Do native speakers use ZVE or CPU?

To accent or not to accent in Greek

What does "Fotze" really mean?



Validating a Url in Node.js


What is the best regular expression to check if a string is a valid URL?What is a good regular expression to match a URL?How to validate a url with lots of querystringsNode: Check if URL is safe to requestValidate decimal numbers in JavaScript - IsNumeric()How to validate an email address in JavaScript?Encode URL in JavaScript?Get the current URL with JavaScript?How do I debug Node.js applications?How do I get started with Node.jsWriting files in Node.jsHow do I pass command line arguments to a Node.js program?How to decide when to use Node.js?How to exit in Node.js






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








8















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.










share|improve this question
























  • stackoverflow.com/a/15607801/2025923 will help you

    – Tushar
    Jun 19 '15 at 6:12











  • Why not use url module. npmjs.com/package/url

    – Swaraj Giri
    Jun 19 '15 at 6:15











  • When you say validate, do you mean ONLY that it is a legal URL or do you mean that the URL actually works and reaches a live site? Does it have to be an absolute URL or are relative URLs alllowed? And, what protocols do you want to accept? Only http? http and https? What about other protocols? You've left a lot of questions unanswered. When you say you want to accept "google.com", what does that mean? It doesn't have a protocol.

    – jfriend00
    Jun 19 '15 at 6:16












  • By validate i mean that URL actually works and reaches a live site,i want to work with http and https protocols only,let me know if you still needs any information.

    – Arslan Sohail
    Jun 19 '15 at 6:18











  • possible duplicate of What is the best regular expression to check if a string is a valid URL?

    – A-312
    Jun 19 '15 at 6:39

















8















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.










share|improve this question
























  • stackoverflow.com/a/15607801/2025923 will help you

    – Tushar
    Jun 19 '15 at 6:12











  • Why not use url module. npmjs.com/package/url

    – Swaraj Giri
    Jun 19 '15 at 6:15











  • When you say validate, do you mean ONLY that it is a legal URL or do you mean that the URL actually works and reaches a live site? Does it have to be an absolute URL or are relative URLs alllowed? And, what protocols do you want to accept? Only http? http and https? What about other protocols? You've left a lot of questions unanswered. When you say you want to accept "google.com", what does that mean? It doesn't have a protocol.

    – jfriend00
    Jun 19 '15 at 6:16












  • By validate i mean that URL actually works and reaches a live site,i want to work with http and https protocols only,let me know if you still needs any information.

    – Arslan Sohail
    Jun 19 '15 at 6:18











  • possible duplicate of What is the best regular expression to check if a string is a valid URL?

    – A-312
    Jun 19 '15 at 6:39













8












8








8


7






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.










share|improve this question
















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.







javascript node.js






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jun 19 '15 at 9:13







Arslan Sohail

















asked Jun 19 '15 at 6:11









Arslan SohailArslan Sohail

9851 gold badge8 silver badges17 bronze badges




9851 gold badge8 silver badges17 bronze badges












  • stackoverflow.com/a/15607801/2025923 will help you

    – Tushar
    Jun 19 '15 at 6:12











  • Why not use url module. npmjs.com/package/url

    – Swaraj Giri
    Jun 19 '15 at 6:15











  • When you say validate, do you mean ONLY that it is a legal URL or do you mean that the URL actually works and reaches a live site? Does it have to be an absolute URL or are relative URLs alllowed? And, what protocols do you want to accept? Only http? http and https? What about other protocols? You've left a lot of questions unanswered. When you say you want to accept "google.com", what does that mean? It doesn't have a protocol.

    – jfriend00
    Jun 19 '15 at 6:16












  • By validate i mean that URL actually works and reaches a live site,i want to work with http and https protocols only,let me know if you still needs any information.

    – Arslan Sohail
    Jun 19 '15 at 6:18











  • possible duplicate of What is the best regular expression to check if a string is a valid URL?

    – A-312
    Jun 19 '15 at 6:39

















  • stackoverflow.com/a/15607801/2025923 will help you

    – Tushar
    Jun 19 '15 at 6:12











  • Why not use url module. npmjs.com/package/url

    – Swaraj Giri
    Jun 19 '15 at 6:15











  • When you say validate, do you mean ONLY that it is a legal URL or do you mean that the URL actually works and reaches a live site? Does it have to be an absolute URL or are relative URLs alllowed? And, what protocols do you want to accept? Only http? http and https? What about other protocols? You've left a lot of questions unanswered. When you say you want to accept "google.com", what does that mean? It doesn't have a protocol.

    – jfriend00
    Jun 19 '15 at 6:16












  • By validate i mean that URL actually works and reaches a live site,i want to work with http and https protocols only,let me know if you still needs any information.

    – Arslan Sohail
    Jun 19 '15 at 6:18











  • possible duplicate of What is the best regular expression to check if a string is a valid URL?

    – A-312
    Jun 19 '15 at 6:39
















stackoverflow.com/a/15607801/2025923 will help you

– Tushar
Jun 19 '15 at 6:12





stackoverflow.com/a/15607801/2025923 will help you

– Tushar
Jun 19 '15 at 6:12













Why not use url module. npmjs.com/package/url

– Swaraj Giri
Jun 19 '15 at 6:15





Why not use url module. npmjs.com/package/url

– Swaraj Giri
Jun 19 '15 at 6:15













When you say validate, do you mean ONLY that it is a legal URL or do you mean that the URL actually works and reaches a live site? Does it have to be an absolute URL or are relative URLs alllowed? And, what protocols do you want to accept? Only http? http and https? What about other protocols? You've left a lot of questions unanswered. When you say you want to accept "google.com", what does that mean? It doesn't have a protocol.

– jfriend00
Jun 19 '15 at 6:16






When you say validate, do you mean ONLY that it is a legal URL or do you mean that the URL actually works and reaches a live site? Does it have to be an absolute URL or are relative URLs alllowed? And, what protocols do you want to accept? Only http? http and https? What about other protocols? You've left a lot of questions unanswered. When you say you want to accept "google.com", what does that mean? It doesn't have a protocol.

– jfriend00
Jun 19 '15 at 6:16














By validate i mean that URL actually works and reaches a live site,i want to work with http and https protocols only,let me know if you still needs any information.

– Arslan Sohail
Jun 19 '15 at 6:18





By validate i mean that URL actually works and reaches a live site,i want to work with http and https protocols only,let me know if you still needs any information.

– Arslan Sohail
Jun 19 '15 at 6:18













possible duplicate of What is the best regular expression to check if a string is a valid URL?

– A-312
Jun 19 '15 at 6:39





possible duplicate of What is the best regular expression to check if a string is a valid URL?

– A-312
Jun 19 '15 at 6:39












3 Answers
3






active

oldest

votes


















26














Checking if a URL is live



This is a bit of a hack, but 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




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");
);


  • check out net-ping package


3rd step



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



var request = require('request');
request(method: 'HEAD', uri:'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

  • @Jan Jůna commented that it's better to use HEAD. He's completely right. Note that not all web servers support HEAD method

  • 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






share|improve this answer

























  • OP apparently wants to know if the URL reaches a live site.

    – jfriend00
    Jun 19 '15 at 6:50











  • thanks @jfriend00, edited.

    – Jossef Harush
    Jun 19 '15 at 7:42






  • 2





    In the 3rd step, you do not have to send GET request. Simple HEAD request will tell you exactly the same and it will not download whole content.

    – Jan Jůna
    Oct 31 '16 at 11:19


















1














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');

);





share|improve this answer


















  • 2





    what does good and bad url refer to? and what is res? please be more specific for the ones who doesn't use node a lot

    – Christoffer
    Jul 23 '18 at 21:45


















0














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





share|improve this answer

























  • Does not work with invalid protocol stringIsAValidUrl("abc://www.example.com:777/a/b"); //true

    – Stephane Janicaud
    Jun 6 at 7:58











  • @StephaneJanicaud It is still valid. abc could be a custom protocol registered on the OS to be handled by a specific app. The question is about validiatiing a URI which this function does. If you want to restrict protocol you can do it with further parsing the URI.

    – pouya
    Jun 6 at 8:15











  • The question is : "Please note i only expect the underlying protocols to be HTTP or HTTPS", you answer does not match this requirement.

    – Stephane Janicaud
    Jun 6 at 8:30











  • @StephaneJanicaud not a big deal. See my updated answer. As i said before there is no need to use third party library. Node.js url module can parse and validate any url.

    – pouya
    Jun 6 at 9:21











  • You're absolutely right, I'm also using this module to validate urls. The problem was the protocol, not the validation method. Thanx for the update.

    – Stephane Janicaud
    Jun 6 at 9:31













Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f30931079%2fvalidating-a-url-in-node-js%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























3 Answers
3






active

oldest

votes








3 Answers
3






active

oldest

votes









active

oldest

votes






active

oldest

votes









26














Checking if a URL is live



This is a bit of a hack, but 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




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");
);


  • check out net-ping package


3rd step



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



var request = require('request');
request(method: 'HEAD', uri:'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

  • @Jan Jůna commented that it's better to use HEAD. He's completely right. Note that not all web servers support HEAD method

  • 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






share|improve this answer

























  • OP apparently wants to know if the URL reaches a live site.

    – jfriend00
    Jun 19 '15 at 6:50











  • thanks @jfriend00, edited.

    – Jossef Harush
    Jun 19 '15 at 7:42






  • 2





    In the 3rd step, you do not have to send GET request. Simple HEAD request will tell you exactly the same and it will not download whole content.

    – Jan Jůna
    Oct 31 '16 at 11:19















26














Checking if a URL is live



This is a bit of a hack, but 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




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");
);


  • check out net-ping package


3rd step



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



var request = require('request');
request(method: 'HEAD', uri:'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

  • @Jan Jůna commented that it's better to use HEAD. He's completely right. Note that not all web servers support HEAD method

  • 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






share|improve this answer

























  • OP apparently wants to know if the URL reaches a live site.

    – jfriend00
    Jun 19 '15 at 6:50











  • thanks @jfriend00, edited.

    – Jossef Harush
    Jun 19 '15 at 7:42






  • 2





    In the 3rd step, you do not have to send GET request. Simple HEAD request will tell you exactly the same and it will not download whole content.

    – Jan Jůna
    Oct 31 '16 at 11:19













26












26








26







Checking if a URL is live



This is a bit of a hack, but 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




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");
);


  • check out net-ping package


3rd step



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



var request = require('request');
request(method: 'HEAD', uri:'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

  • @Jan Jůna commented that it's better to use HEAD. He's completely right. Note that not all web servers support HEAD method

  • 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






share|improve this answer















Checking if a URL is live



This is a bit of a hack, but 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




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");
);


  • check out net-ping package


3rd step



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



var request = require('request');
request(method: 'HEAD', uri:'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

  • @Jan Jůna commented that it's better to use HEAD. He's completely right. Note that not all web servers support HEAD method

  • 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







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 20 '18 at 13:29

























answered Jun 19 '15 at 6:19









Jossef HarushJossef Harush

17.3k4 gold badges67 silver badges76 bronze badges




17.3k4 gold badges67 silver badges76 bronze badges












  • OP apparently wants to know if the URL reaches a live site.

    – jfriend00
    Jun 19 '15 at 6:50











  • thanks @jfriend00, edited.

    – Jossef Harush
    Jun 19 '15 at 7:42






  • 2





    In the 3rd step, you do not have to send GET request. Simple HEAD request will tell you exactly the same and it will not download whole content.

    – Jan Jůna
    Oct 31 '16 at 11:19

















  • OP apparently wants to know if the URL reaches a live site.

    – jfriend00
    Jun 19 '15 at 6:50











  • thanks @jfriend00, edited.

    – Jossef Harush
    Jun 19 '15 at 7:42






  • 2





    In the 3rd step, you do not have to send GET request. Simple HEAD request will tell you exactly the same and it will not download whole content.

    – Jan Jůna
    Oct 31 '16 at 11:19
















OP apparently wants to know if the URL reaches a live site.

– jfriend00
Jun 19 '15 at 6:50





OP apparently wants to know if the URL reaches a live site.

– jfriend00
Jun 19 '15 at 6:50













thanks @jfriend00, edited.

– Jossef Harush
Jun 19 '15 at 7:42





thanks @jfriend00, edited.

– Jossef Harush
Jun 19 '15 at 7:42




2




2





In the 3rd step, you do not have to send GET request. Simple HEAD request will tell you exactly the same and it will not download whole content.

– Jan Jůna
Oct 31 '16 at 11:19





In the 3rd step, you do not have to send GET request. Simple HEAD request will tell you exactly the same and it will not download whole content.

– Jan Jůna
Oct 31 '16 at 11:19













1














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');

);





share|improve this answer


















  • 2





    what does good and bad url refer to? and what is res? please be more specific for the ones who doesn't use node a lot

    – Christoffer
    Jul 23 '18 at 21:45















1














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');

);





share|improve this answer


















  • 2





    what does good and bad url refer to? and what is res? please be more specific for the ones who doesn't use node a lot

    – Christoffer
    Jul 23 '18 at 21:45













1












1








1







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');

);





share|improve this answer













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');

);






share|improve this answer












share|improve this answer



share|improve this answer










answered Feb 17 '18 at 15:04









MSiMSi

613 bronze badges




613 bronze badges







  • 2





    what does good and bad url refer to? and what is res? please be more specific for the ones who doesn't use node a lot

    – Christoffer
    Jul 23 '18 at 21:45












  • 2





    what does good and bad url refer to? and what is res? please be more specific for the ones who doesn't use node a lot

    – Christoffer
    Jul 23 '18 at 21:45







2




2





what does good and bad url refer to? and what is res? please be more specific for the ones who doesn't use node a lot

– Christoffer
Jul 23 '18 at 21:45





what does good and bad url refer to? and what is res? please be more specific for the ones who doesn't use node a lot

– Christoffer
Jul 23 '18 at 21:45











0














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





share|improve this answer

























  • Does not work with invalid protocol stringIsAValidUrl("abc://www.example.com:777/a/b"); //true

    – Stephane Janicaud
    Jun 6 at 7:58











  • @StephaneJanicaud It is still valid. abc could be a custom protocol registered on the OS to be handled by a specific app. The question is about validiatiing a URI which this function does. If you want to restrict protocol you can do it with further parsing the URI.

    – pouya
    Jun 6 at 8:15











  • The question is : "Please note i only expect the underlying protocols to be HTTP or HTTPS", you answer does not match this requirement.

    – Stephane Janicaud
    Jun 6 at 8:30











  • @StephaneJanicaud not a big deal. See my updated answer. As i said before there is no need to use third party library. Node.js url module can parse and validate any url.

    – pouya
    Jun 6 at 9:21











  • You're absolutely right, I'm also using this module to validate urls. The problem was the protocol, not the validation method. Thanx for the update.

    – Stephane Janicaud
    Jun 6 at 9:31















0














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





share|improve this answer

























  • Does not work with invalid protocol stringIsAValidUrl("abc://www.example.com:777/a/b"); //true

    – Stephane Janicaud
    Jun 6 at 7:58











  • @StephaneJanicaud It is still valid. abc could be a custom protocol registered on the OS to be handled by a specific app. The question is about validiatiing a URI which this function does. If you want to restrict protocol you can do it with further parsing the URI.

    – pouya
    Jun 6 at 8:15











  • The question is : "Please note i only expect the underlying protocols to be HTTP or HTTPS", you answer does not match this requirement.

    – Stephane Janicaud
    Jun 6 at 8:30











  • @StephaneJanicaud not a big deal. See my updated answer. As i said before there is no need to use third party library. Node.js url module can parse and validate any url.

    – pouya
    Jun 6 at 9:21











  • You're absolutely right, I'm also using this module to validate urls. The problem was the protocol, not the validation method. Thanx for the update.

    – Stephane Janicaud
    Jun 6 at 9:31













0












0








0







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





share|improve this answer















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






share|improve this answer














share|improve this answer



share|improve this answer








edited Jun 6 at 9:18

























answered Apr 9 at 5:23









pouyapouya

7492 gold badges15 silver badges29 bronze badges




7492 gold badges15 silver badges29 bronze badges












  • Does not work with invalid protocol stringIsAValidUrl("abc://www.example.com:777/a/b"); //true

    – Stephane Janicaud
    Jun 6 at 7:58











  • @StephaneJanicaud It is still valid. abc could be a custom protocol registered on the OS to be handled by a specific app. The question is about validiatiing a URI which this function does. If you want to restrict protocol you can do it with further parsing the URI.

    – pouya
    Jun 6 at 8:15











  • The question is : "Please note i only expect the underlying protocols to be HTTP or HTTPS", you answer does not match this requirement.

    – Stephane Janicaud
    Jun 6 at 8:30











  • @StephaneJanicaud not a big deal. See my updated answer. As i said before there is no need to use third party library. Node.js url module can parse and validate any url.

    – pouya
    Jun 6 at 9:21











  • You're absolutely right, I'm also using this module to validate urls. The problem was the protocol, not the validation method. Thanx for the update.

    – Stephane Janicaud
    Jun 6 at 9:31

















  • Does not work with invalid protocol stringIsAValidUrl("abc://www.example.com:777/a/b"); //true

    – Stephane Janicaud
    Jun 6 at 7:58











  • @StephaneJanicaud It is still valid. abc could be a custom protocol registered on the OS to be handled by a specific app. The question is about validiatiing a URI which this function does. If you want to restrict protocol you can do it with further parsing the URI.

    – pouya
    Jun 6 at 8:15











  • The question is : "Please note i only expect the underlying protocols to be HTTP or HTTPS", you answer does not match this requirement.

    – Stephane Janicaud
    Jun 6 at 8:30











  • @StephaneJanicaud not a big deal. See my updated answer. As i said before there is no need to use third party library. Node.js url module can parse and validate any url.

    – pouya
    Jun 6 at 9:21











  • You're absolutely right, I'm also using this module to validate urls. The problem was the protocol, not the validation method. Thanx for the update.

    – Stephane Janicaud
    Jun 6 at 9:31
















Does not work with invalid protocol stringIsAValidUrl("abc://www.example.com:777/a/b"); //true

– Stephane Janicaud
Jun 6 at 7:58





Does not work with invalid protocol stringIsAValidUrl("abc://www.example.com:777/a/b"); //true

– Stephane Janicaud
Jun 6 at 7:58













@StephaneJanicaud It is still valid. abc could be a custom protocol registered on the OS to be handled by a specific app. The question is about validiatiing a URI which this function does. If you want to restrict protocol you can do it with further parsing the URI.

– pouya
Jun 6 at 8:15





@StephaneJanicaud It is still valid. abc could be a custom protocol registered on the OS to be handled by a specific app. The question is about validiatiing a URI which this function does. If you want to restrict protocol you can do it with further parsing the URI.

– pouya
Jun 6 at 8:15













The question is : "Please note i only expect the underlying protocols to be HTTP or HTTPS", you answer does not match this requirement.

– Stephane Janicaud
Jun 6 at 8:30





The question is : "Please note i only expect the underlying protocols to be HTTP or HTTPS", you answer does not match this requirement.

– Stephane Janicaud
Jun 6 at 8:30













@StephaneJanicaud not a big deal. See my updated answer. As i said before there is no need to use third party library. Node.js url module can parse and validate any url.

– pouya
Jun 6 at 9:21





@StephaneJanicaud not a big deal. See my updated answer. As i said before there is no need to use third party library. Node.js url module can parse and validate any url.

– pouya
Jun 6 at 9:21













You're absolutely right, I'm also using this module to validate urls. The problem was the protocol, not the validation method. Thanx for the update.

– Stephane Janicaud
Jun 6 at 9:31





You're absolutely right, I'm also using this module to validate urls. The problem was the protocol, not the validation method. Thanx for the update.

– Stephane Janicaud
Jun 6 at 9:31

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f30931079%2fvalidating-a-url-in-node-js%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현