Categories
JavaScript Answers

How to validate a URL in Node.js?

Spread the love

You can validate a URL in Node.js using regular expressions or by utilizing built-in modules like url.

We can do this 2 ways.

Using Regular Expressions:

function isValidURL(url) {
    // Regular expression for a valid URL
    var urlRegex = /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|localhost)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
    return urlRegex.test(url);
}

// Example usage:
console.log(isValidURL("https://www.example.com")); // Output: true
console.log(isValidURL("ftp://ftp.example.com/file.txt")); // Output: true
console.log(isValidURL("not_a_url")); // Output: false

Using the url Module:

const url = require('url');

function isValidURL(urlString) {
    try {
        new URL(urlString);
        return true;
    } catch (error) {
        return false;
    }
}

// Example usage:
console.log(isValidURL("https://www.example.com")); // Output: true
console.log(isValidURL("ftp://ftp.example.com/file.txt")); // Output: true
console.log(isValidURL("not_a_url")); // Output: false

Both methods provide a way to check if a given string is a valid URL.

The second method using the url module is more concise and reliable because it leverages built-in functionality.

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 *