Regex for URL Validation
Validates a web URL including http/https protocols.
Understanding The Regex Pattern
/^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/- https://www.example.com
- http://sub.example.co.uk/path?q=1
- www.example.com
- https://
- htp://example.com
How this Pattern Works
URL validation is a critical security and data quality step when accepting user-submitted links in profile settings, comment sections, or content management systems. This regex pattern rigorously verifies that the provided string is a valid web address. It explicitly requires the string to start with either 'http://' or 'https://', ensuring that only secure and standard web protocols are accepted while blocking localized file paths like 'file://' or malicious schemes.
Following the protocol, the regex looks for an optional 'www.' subdomain and then enforces standard domain name constraints, ensuring the domain consists of valid alphanumeric characters and hyphens. It specifies that the domain must end with a valid top-level domain (TLD) extension, ranging from 1 to 6 characters. Furthermore, the pattern seamlessly captures any valid path directories, complex query parameters (such as those containing ampersands, equals signs, and question marks), or fragment identifiers (hash symbols used for page anchors).
By utilizing this regular expression, developers can prevent broken links on their platforms, enhance user experience, and mitigate the risk of users submitting non-URL payloads. It acts as a crucial first line of defense against certain types of cross-site scripting (XSS) and server-side request forgery (SSRF) vulnerabilities by ensuring the input strictly conforms to the expected URL structure before any further processing or fetching occurs.
Implement The Regex In Your Code
const regex = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$/;
regex.test('https://example.com');import re
regex = re.compile(r'^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$')
bool(regex.match('https://example.com'))import "regexp"
matched, _ := regexp.MatchString(`^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$`, "https://example.com")use regex::Regex;
let re = Regex::new(r"^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b(?:[-a-zA-Z0-9()@:%_\+.~#?&\/=]*)$").unwrap();
re.is_match("https://example.com")