Validating a URL in Node.js
Solution 1
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
Solution 2
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;
}
};
Solution 3
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');
}
});
Solution 4
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
Solution 5
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`);
}
Arslan Sohail
I'm an Android developer with 4 years of experience. I know how you should develop an application from scratch and how to maintain and scale it properly. I'm aware of what are the day-by-day problems of developing an widely used application, and I have acquired experience in defining which is the best approach to solve them. I believe I develop some well-thought solutions always anticipating future problems and design changes. I have experience in building network-based applications in Android using Retrofit. I also am a big fan of exploring different Android architectures and understand which are the ones that are most suitable to the problems we have to face at the present, and the ones that we will probably face in the future. I'm really interested about the Android community and what is happening at each moment, in order know which are the best tools, the current trends and the what is fresh in the Android world. I have worked with different developing methodologies such as Scrum , and I always worked in teams. I can assure that I am a team-player, which loves to share the victories in a group. My biggest asset is my passion to learn. I love to feel that I'm constantly improving at the personal level and at my technical skills.
Updated on July 21, 2021Comments
-
Arslan Sohail almost 3 years
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 returnfalse
.