Input validation
Validate request, form, or configuration fields that must be textual.
Zod · Function
z.string() creates a Zod schema for validating strings. Chain its string-specific checks and transformations, then parse input with parse or safeParse.
z.string() creates a schema that accepts strings. Chain string-specific checks such as minimum and maximum length, then use parse to return validated data or safeParse to receive a success/error result without throwing.
z.string()A Zod string schema that validates string input and exposes string-specific validation and transformation methods.
import { z } from "zod";
const username = z.string().min(3).max(20);
console.log(username.parse("ada"));
console.log(username.safeParse(42).success);Creates a string schema with length constraints, then demonstrates successful parsing and non-throwing failure handling.
Validate request, form, or configuration fields that must be textual.
Add minimum, maximum, exact-length, or pattern constraints to identifiers and labels.
Normalize casing while validating text values.
z.string() constructs a schema whose input must be a JavaScript string. Parsing a non-string value fails validation, while a valid string is returned unchanged unless additional checks or transforms are chained.
Follow-up: How would you enforce a bounded username? Chain .min(3).max(20) and parse the input, or use safeParse when the caller should receive a result instead of an exception.
It provides string-specific APIs for constraints and transformations. The documented examples include max, min, length, regex, startsWith, endsWith, includes, uppercase, and lowercase.
Follow-up: How can a schema require a pattern and length at once? Compose the checks, for example z.string().min(3).regex(/^[a-z]+$/).
parse returns validated data and throws when validation fails. safeParse performs the same validation but returns an object with success and either data or an error, making it suitable for explicit error handling.
Follow-up: When should safeParse be preferred? Use it at boundaries where invalid input is expected and should be represented as a value rather than raised as an exception.
z.coerce.string()z.email()z.url()z.regex()z.string().min()z.string().max()z.string().regex()