← Back to all snippets
JAVASCRIPT

Robust URL Validation using Regular Expressions

Implement client-side URL validation with a comprehensive regular expression to check for valid HTTP/HTTPS protocols, domains, and paths in web applications.

function isValidURL(url) {
  const urlRegex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
  return urlRegex.test(url);
}

// Examples:
console.log(isValidURL("http://www.example.com")); // true
console.log(isValidURL("https://sub.domain.net/path/page.html")); // true
console.log(isValidURL("example.com")); // true
console.log(isValidURL("ftp://invalid.com")); // false
console.log(isValidURL("not-a-url")); // false
How it works: This function validates URLs using a regular expression. It supports both HTTP and HTTPS protocols (optional), common domain name structures, and various paths. While not exhaustive for all edge cases, it covers most common valid URL formats, making it suitable for quick client-side checks on user-provided links.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs