Skip to content

Attributes Reference

The #[zod(...)] attribute configures validation constraints on struct fields.

AttributeDescriptionExample
min_length(n)Minimum string length#[zod(min_length(3))]
max_length(n)Maximum string length#[zod(max_length(50))]
length(n)Exact string length#[zod(length(2))]
emailEmail format#[zod(email)]
urlURL format#[zod(url)]
regex("pattern")Regex pattern#[zod(regex(r"^[a-z]+$"))]
starts_with("value")Starts with prefix#[zod(starts_with("hello"))]
ends_with("value")Ends with suffix#[zod(ends_with("@domain.com"))]
includes("value")Contains substring#[zod(includes("test"))]
AttributeDescriptionExample
min(n)Minimum value#[zod(min(0.0))]
max(n)Maximum value#[zod(max(100.0))]
intInteger only#[zod(int)]
positiveMust be > 0#[zod(positive)]
negativeMust be < 0#[zod(negative)]
nonnegativeMust be >= 0#[zod(nonnegative)]
nonpositiveMust be <= 0#[zod(nonpositive)]
finiteMust be finite#[zod(finite)]
AttributeDescriptionExample
min_length(n)Minimum array length#[zod(min_length(1))]
max_length(n)Maximum array length#[zod(max_length(10))]
length(n)Exact array length#[zod(length(3))]

Multiple attributes can be combined in a single #[zod(...)]:

#[derive(ZodSchema)]
struct Registration {
#[zod(min_length(3), max_length(20), regex(r"^[a-zA-Z0-9_]+$"))]
username: String,
#[zod(min(13.0), max(120.0), int)]
age: u32,
#[zod(min_length(1), max_length(5))]
tags: Vec<String>,
}

Fields without #[zod(...)] attributes use the default schema for their type:

#[derive(ZodSchema)]
struct Simple {
name: String, // string() — no extra validation
count: u32, // number().int()
active: bool, // boolean()
items: Vec<String>, // array(string())
bio: Option<String>, // optional(string())
}