Course contentsShow
← Web Development
Lesson 948 of 2,98217. URL and History ManagementFree lesson

URL Validation Techniques

Validate URLs by attempting to construct a URL object and catching errors for malformed inputs.

URL Validation Techniques

What you'll learn: How to programmatically check whether a string is a valid URL using JavaScript's built-in error detection.

Why Validation Matters

When users enter URLs or your code constructs them dynamically, you need to verify they're actually valid before using them. A malformed URL can crash your application or lead to unexpected behavior. Rather than writing complex regular expressions, JavaScript provides a simple validation technique: try to build it and see if it breaks.

Using the URL Constructor as a Validator

The URL constructor throws an error when given invalid input. You can catch this error to determine validity:

function isValidURL(urlString) {
  try {
    new URL(urlString);
    return true;
  } catch (error) {
    return false;
  }
}

// Test cases
console.log(isValidURL('https://example.com')); // true
console.log(isValidURL('not a url'));            // false
console.log(isValidURL('ftp://files.org'));      // true
console.log(isValidURL('example.com'));          // false (no protocol)

The Try-Catch Pattern

Think of this like testing if a key fits a lock. You don't need to measure the key—just try inserting it. If it works, it's valid; if not, it's not.

The try block attempts to create a URL object. If the string is malformed (missing protocol, invalid characters, etc.), JavaScript throws a TypeError. The catch block intercepts this error, preventing it from crashing your code.

Practical Validation

const userInput = document.querySelector('#url-input').value;

if (isValidURL(userInput)) {
  const url = new URL(userInput);
  window.location.href = url.href; // Safe to navigate
} else {
  alert('Please enter a valid URL');
}

Key Takeaway: Validate URLs by wrapping new URL() in a try-catch block—if construction fails, the string isn't a valid URL.