Write a URL validation regex
URL validation regex must handle protocol, domain, port, path, query, and fragment. Learn practical patterns and when to use a URL parser instead.
- 1
A URL has: scheme://host:port/path?query#fragment. A practical regex: ^https?://[a-zA-Z0-9.-]+(:\d+)?(/[^\s]*)?$ validates basic structure. For full RFC 3986 compliance, use a URL parser instead of regex — URLs can contain encoded characters, IPv6 addresses in brackets, and complex query strings that regex handles poorly.
- 2 Regex Tester →
Test URL patterns. Simple: ^https?://\S+$ catches obvious non-URLs. Moderate: ^https?://[a-zA-Z0-9.-]+(:\d+)?(/[^\s]*)?$ checks structure. Test against valid URLs (http://example.com, https://sub.example.co.uk:8080/path?q=1#frag) and invalid ones (missing protocol, spaces, no host).
- 3 URL Parser →
Use a URL parser instead of regex for full validation. The parser handles all URL components, encoding, IPv6, and relative URLs. It is more reliable than regex for URL validation. Use regex only for quick checks; use a parser for production validation.
Frequently asked questions
- Regex or URL parser for validation?
- Use a URL parser (URL constructor in JavaScript, urllib.parse in Python) for production validation. It handles all RFC 3986 cases that regex cannot (IPv6, encoded characters, relative URLs). Use regex only for quick client-side hints or when you control the URL format.
- Should I require http/https?
- For web URLs, yes — require https (and optionally http for development). For general URIs, allow other schemes (ftp, mailto, file, custom). The scheme determines the rest of the format, so validate per-scheme. For user input, use a URL parser and check the protocol explicitly.
Workflows that solve this
Learn more
Want to understand why?