🔗URL & UTM

URL Validation & Format Checking

Validate URL format and check for common issues

Explanation

Validate URLs for proper protocol, domain, and structure before processing or storing.

Examples

Valid URL
Input
https://example.com/path
Output
✓ Valid
Invalid - no protocol
Input
example.com
Output
✗ Invalid
Invalid - bad format
Input
ht!tp://bad url.com
Output
✗ Invalid

Code Examples

JavaScript
// Using URL constructor (throws on invalid)
function isValidURL(string) {
  try {
    new URL(string);
    return true;
  } catch (err) {
    return false;
  }
}

// With protocol check
function isValidHTTPURL(string) {
  try {
    const url = new URL(string);
    return url.protocol === 'http:' || url.protocol === 'https:';
  } catch (err) {
    return false;
  }
}

// Regex validation (less reliable)
function isValidURLRegex(string) {
  const pattern = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/;
  return pattern.test(string);
}

// Comprehensive validation
function validateURL(string) {
  const errors = [];
  
  try {
    const url = new URL(string);
    
    // Check protocol
    if (!['http:', 'https:'].includes(url.protocol)) {
      errors.push('Protocol must be http or https');
    }
    
    // Check domain
    if (!url.hostname) {
      errors.push('Missing hostname');
    }
    
    // Check for spaces
    if (string.includes(' ')) {
      errors.push('URL contains spaces');
    }
    
    // Check for common typos
    if (url.hostname.startsWith('www..')) {
      errors.push('Invalid hostname (double dots)');
    }
    
    return {
      valid: errors.length === 0,
      errors,
      url
    };
  } catch (err) {
    return {
      valid: false,
      errors: ['Invalid URL format'],
      url: null
    };
  }
}

// Usage
console.log(isValidURL('https://example.com')); // true
console.log(isValidURL('not a url')); // false

const result = validateURL('https://example.com/path?query=1');
console.log(result);
// { valid: true, errors: [], url: URL {...} }

Try it Now

💡 Tips

  • URL constructor is best for validation
  • Check for protocol (http/https) explicitly
  • Validate domain has valid TLD
  • Check for spaces and special characters
  • Consider internationalized domains (IDN)
  • Validate URL length (max ~2000 chars)
  • Test with real user inputs

⚠️ Common Pitfalls

  • Regex validation is complex and error-prone
  • URL constructor allows any valid URL (ftp://, etc.)
  • Doesn't check if URL actually exists
  • May need to normalize URLs before comparison
  • Trailing slashes can cause duplicate URLs