Generic URL validation
Accepting general URL-like input, including schemes such as mailto.
Zod · Module
z.url() validates WHATWG-compatible URL strings. Optional protocol and hostname regular expressions let you narrow the accepted URLs.
z.url() creates a schema for validating WHATWG-compatible URL strings. It uses the runtime's URL constructor and can optionally constrain the protocol and hostname with regular expressions; validation returns the original string when parsing succeeds and throws a ZodError when it fails.
z.url(options?)| Name | Type | Description |
|---|---|---|
hostname | RegExp | Optional regular expression used to constrain the URL hostname. |
protocol | RegExp | Optional regular expression used to constrain the URL protocol. |
A Zod schema that validates URL strings and returns the original string on successful parsing.
z.url() to build a schema for WHATWG-compatible URL strings.URL constructor.hostname regular expression when the URL must target a particular host pattern.protocol regular expression to restrict the accepted URL schemes.z.httpUrl() for web-specific validation rather than the broader generic URL schema.z.url() accepts more than ordinary web URLs, including values such as localhost and mailto URLs. Use z.httpUrl() when the input must use HTTP or HTTPS and have a valid domain hostname.URL implementation, so acceptance can vary between JavaScript platforms or runtimes.import { z } from "zod";
const urlSchema = z.url({
protocol: /^https?$/,
hostname: /^example\.com$/,
});
console.log(urlSchema.parse("https://example.com/docs"));
// urlSchema.parse("http://zombo.com"); // throws a ZodErrorCreates a URL schema restricted to HTTP(S) URLs whose hostname is example.com.
Accepting general URL-like input, including schemes such as mailto.
Allowing only HTTP or HTTPS URLs with a domain hostname.
Restricting links to a known host or protocol pattern.
z.url() validate and what implementation does it use?z.url() validates WHATWG-compatible URL strings and relies internally on the new URL() constructor. A successful parse returns the input string; an invalid value causes Zod validation to fail.
Follow-up: How would you restrict the accepted URL schemes? Pass a protocol regular expression, such as /^https?$/, to allow only HTTP and HTTPS.
Pass a hostname regular expression in the options object. For example, z.url({ hostname: /^example\.com$/ }) accepts a matching hostname and rejects other hostnames.
Follow-up: How would you constrain both host and scheme? Supply both hostname and protocol options in the same call.
z.httpUrl() be preferred over z.url()?Use z.httpUrl() when validating web URLs specifically. The documented equivalent restricts the protocol to http or https and checks the hostname with z.regexes.domain.
Follow-up: Why not use z.url() alone for web URLs? It is intentionally permissive and also accepts non-web schemes such as mailto.
z.httpUrl()z.regexes.domainnew URL()