DeveloperBreeze

Url Validation With Url Constructor Development Tutorials, Guides & Insights

Unlock 1+ expert-curated url validation with url constructor tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your url validation with url constructor skills on DeveloperBreeze.

Different Ways to Validate URLs in JavaScript

Tutorial August 29, 2024

For production environments, it's often best to combine multiple methods for comprehensive validation.

function validateURL(url) {
    try {
        // First, use the URL constructor
        new URL(url);
    } catch (e) {
        return false;
    }

    // Then, validate against a regex pattern
    const pattern = new RegExp('^(https?:\\/\\/)?' +
        '((([a-zA-Z0-9\\-\\.]+)\\.([a-zA-Z]{2,}))|' +
        'localhost|' +
        '((\\d{1,3}\\.){3}\\d{1,3}))' +
        '(\\:\\d+)?(\\/[-a-zA-Z0-9%_@.&+=~]*)*$', 'i');

    return pattern.test(url);
}

console.log(validateURL('https://developerbreeze.com')); // true
console.log(validateURL('invalid-url')); // false