---
title: "Validate URLs with the URL constructor · Ihab Khattab"
description: "A nice way to validate a URL without a regex: let new URL() try to parse it."
url: "https://ihabkhattab.com/til/validate-url-with-url-constructor/"
---

# Validate URLs with the URL constructor

Aug 22, 2022 · [Also on X](https://x.com/HO_BA/status/1561733178368335877)

A nice way to validate a URL without a regex: let `new URL()` try to parse it.

```ts
/**
 * Check if supplied href is a valid URL or not.
 * Note "example.com/contact" is not a valid URL.
 * The protocol has to be supplied as well:
 * => "https://example.com/contact"
 * => "mailto:iron.man@gmail.com"
 * => "tel:+188899956754"
 */
function isUrl(href: string) {
  try {
    new URL(href);
    return true;
  } catch (e) {
    return false;
  }
}
```

Via [André Landgraf’s remix-isomorphic-link](https://github.com/andrelandgraf/remix-isomorphic-link/blob/main/src/index.tsx#L48-L63).

Update: browsers now ship this built in. `URL.canParse(href)` returns a boolean, no try/catch needed.

[← All TILs](https://ihabkhattab.com/til/)
