validateURL
Validates whether a string is a well-formed URL.
1/**
2 * Validates whether a string is a well-formed URL.
3 *
4 * @param url - The string to validate.
5 * @returns True if the string is a valid URL, otherwise false.
6 */
7export function validateURL(url: string): boolean {
8 try {
9 new URL(url);
10 return true;
11 } catch {
12 return false;
13 }
14}
Native API Usage
Leverages the built-in
URL
constructor for accurate and standards-compliant validation without relying on regular expressions.Broad Format Support
Correctly recognizes a wide range of valid URL schemes and structures (e.g., with/without protocols, ports, query parameters).
Minimal Overhead
Simple, fast, and lightweight — ideal for high-frequency validations with negligible performance impact.
Robust Error Handling
Reliably catches malformed input through
try-catch
, avoiding crashes or unhandled exceptions.
Tests | Examples
1test('validateURL - valid HTTP URL', () => {
2 expect(validateURL('http://example.com')).toBe(true);
3});
4
5test('validateURL - valid HTTPS URL', () => {
6 expect(validateURL('https://example.com')).toBe(true);
7});
8
9test('validateURL - valid URL with path and query', () => {
10 expect(validateURL('https://example.com/path?query=1')).toBe(true);
11});
12
13test('validateURL - invalid string', () => {
14 expect(validateURL('not a url')).toBe(false);
15});
16
17test('validateURL - missing protocol', () => {
18 expect(validateURL('example.com')).toBe(false);
19});
20
21test('validateURL - empty string', () => {
22 expect(validateURL('')).toBe(false);
23});
Common Use Cases
Form Validation
Ensure URLs entered by users (e.g., in contact forms, profile links) are properly structured.
Content Moderation or Filtering
Automatically detect and validate URLs in submitted text (e.g., comments, messages).
Link Preview Generation
Pre-check links before attempting to fetch metadata or embed previews.
URL Whitelisting/Blacklisting
Confirm valid structure before applying security rules or matching against a list.
Sanity Checks Before Redirection or Fetch
Prevent errors by validating URLs before using them in navigation or API calls.