JAVASCRIPT
Validate URL Format with Regex (HTTP/HTTPS)
Validate URLs in JavaScript using a regular expression to check for valid HTTP or HTTPS protocols and common domain structures, ideal for form validation.
function validateUrl(url) {
const urlRegex = new RegExp("^(https?://(?:www\.|(?!www))[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,}|www\.[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9]\.[^\s]{2,})$");
return urlRegex.test(url);
}
// Example usage:
console.log(validateUrl("https://www.example.com")); // true
console.log(validateUrl("http://example.org")); // true
console.log(validateUrl("invalid-url")); // false
How it works: This function utilizes a regex pattern to validate if a given string is a well-formed URL, specifically checking for `http://` or `https://` protocols, optionally with `www.`, followed by a domain name and a top-level domain. It's useful for ensuring links provided by users are valid.