isValidURL
Checks whether a string is a valid URL.
1/**
2 * Checks whether a string is a valid URL.
3 *
4 * @param url - The string to validate.
5 * @returns True if the string is a valid URL, false otherwise.
6 */
7export function isValidURL(url: string): boolean {
8 try {
9 new URL(url);
10 return true;
11 } catch {
12 return false;
13 }
14}
Standards-Based Validation
Relies on the built-in
URL
constructor, which adheres to the WHATWG URL specification for reliable parsing.No Regex Complexity
Avoids brittle regular expressions in favor of native parsing logic, reducing maintenance overhead.
Robust Across Schemes
Supports validation of various protocols such as
http
,https
,ftp
, and more.Safe and Efficient
Gracefully handles invalid input using try/catch without causing runtime crashes or performance penalties.
Tests | Examples
1test('validates correct URLs', () => {
2 expect(isValidURL('https://example.com')).toBe(true);
3 expect(isValidURL('http://localhost:3000')).toBe(true);
4 expect(isValidURL('ftp://ftp.example.com')).toBe(true);
5 expect(isValidURL('https://sub.example.co.uk/path?query=123')).toBe(true);
6});
7
8test('invalidates incorrect URLs', () => {
9 expect(isValidURL('not a url')).toBe(false);
10 expect(isValidURL('htp:/example.com')).toBe(false);
11 expect(isValidURL('example.com')).toBe(false); // missing protocol
12 expect(isValidURL('http//:example.com')).toBe(false);
13});
14
15test('invalidates empty and malformed strings', () => {
16 expect(isValidURL('')).toBe(false);
17 expect(isValidURL(' ')).toBe(false);
18});
Common Use Cases
User Input Validation
Ensure URLs entered in forms (e.g., profile links, image sources) are well-formed before submission.
Link Previews and Embeds
Verify URLs before generating previews or embedding third-party content.
Sanitization for Redirects
Validate dynamic redirect targets to prevent open redirect vulnerabilities.
Content Management Systems
Validate links in CMS editors or markdown inputs before saving or rendering.
Bookmarking and Link Storage
Check that saved or imported URLs are valid and parseable before persisting them.