← Back to all snippets
JAVASCRIPT

Validate URL Format with Regex

Implement a JavaScript function to validate URLs, ensuring they follow standard protocols (http/https) and domain structures.

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

// Example usage:
// console.log(isValidURL("https://www.example.com/path")); // true
// console.log(isValidURL("http://example.org")); // true
// console.log(isValidURL("invalid-url")); // false
How it works: The `isValidURL` function utilizes a regular expression to verify if a string is a valid URL. It supports both "http://" and "https://" protocols (optional), common domain structures, and optional paths, making it suitable for basic URL input validation in web forms or data processing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs