Check if a URL is Valid: Regex to the Rescue
Use a JavaScript regex snippet to validate URLs, with a gatekeeper analogy to ensure only proper links pass through.

Shashank
Check if a URL is Valid: Regex to the Rescue
Imagine URLs as guests trying to enter your app’s exclusive party. Some are legit (like https://syntaxsaga.com
), while others are impostors (htp://badurl
). A regex is your gatekeeper, checking credentials to ensure only valid URLs get in. Let’s craft a snippet to validate URLs and keep your app secure.
The Regex Snippet
Here’s a function to check if a URL is valid:
function isValidUrl(url) {
const regex = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([\/\w .-]*)*\/?$/;
return regex.test(url);
}
console.log(isValidUrl('https://syntaxsaga.com')); // Output: true
console.log(isValidUrl('ftp://invalid')); // Output: false
This regex checks for common URL patterns, like http://example.com
or https://sub.domain.co/path
.
Breaking Down the Regex
Let’s decode the gatekeeper’s rules:
Part | Meaning |
---|---|
^(https?:\/\/)? | Optional http:// or https:// |
([\da-z.-]+) | Domain name (letters, digits, dots, hyphens) |
.([a-z.]{2,6}) | Top-level domain (e.g., .com , .co.uk ) |
([\/\w .-]*)* | Optional paths (e.g., /blog/post ) |
\/?$ | Optional trailing slash, end of string |
The test
method returns true
if the URL matches, false
otherwise.
A Real-World Scenario
Suppose you’re building a link-shortener app. Users submit URLs, and you need to validate them:
document.querySelector('#urlInput').addEventListener('input', (e) => {
const url = e.target.value;
if (isValidUrl(url)) {
console.log('Valid URL!');
} else {
console.log('Invalid URL.');
}
});
This ensures only valid URLs are processed, preventing errors or security risks.
Limitations and Enhancements
This regex covers common cases but isn’t perfect. For example, it may reject complex URLs with query parameters or special characters. For production, consider the URL
constructor:
function isValidUrlEnhanced(url) {
try {
new URL(url);
return true;
} catch {
return false;
}
}
console.log(isValidUrlEnhanced('https://example.com?query=1')); // Output: true
The URL
constructor is stricter and supports more edge cases.
Use the URL
constructor for robust validation, but regex is great for quick checks or specific patterns.
Why It Matters
URL validation is critical for form inputs, API requests, and security. Ever wonder why a link broke your app? Invalid URLs are often to blame. This snippet keeps your app’s gates secure.
The Future of URL Validation
As URLs evolve (e.g., with Unicode domains or new protocols), validation will adapt. Libraries like validator.js
build on these patterns, but a solid regex or URL
check is timeless.
What URLs will your app welcome? Try this snippet to guard your app’s gates.