Categories
JavaScript Answers

How to validate a URL in Node.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *