Sometimes, we want to validate a URL in Node.js.
In this article, we’ll look at how to validate a URL in Node.js.
How to validate a URL in Node.js?
To validate a URL in Node.js, we can use the valid-url package.
To install it, we run npm i valid-url
.
Then we can use it by writing:
const validUrl = require('valid-url');
const url = "http://bla.com"
if (validUrl.isUri(url)) {
console.log('Looks like an URI');
}
else {
console.log('Not a URI');
}
We call the validUrl.isUri
method with the url
string to check if url
is a valid URL string.
Since it’s a URL, isUri
should return true
.
Therefore, 'Looks like an URI'
is logged.
Conclusion
To validate a URL in Node.js, we can use the valid-url package.