DeveloperBreeze

Validate Url Input Javascript Development Tutorials, Guides & Insights

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

Different Ways to Validate URLs in JavaScript

Tutorial August 29, 2024

Regular expressions (regex) can be used for URL validation, though they can be more complex and error-prone. Here's a simple regex pattern for validating URLs.

function validateURL(url) {
    const pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
        '((([a-zA-Z0-9\\-\\.]+)\\.([a-zA-Z]{2,}))|' + // domain name
        'localhost|' + // localhost
        '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
        '(\\:\\d+)?(\\/[-a-zA-Z0-9%_@.&+=~]*)*$', 'i'); // port and path

    return pattern.test(url);
}

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