Skip to content

Getting Started

Add zod-rs to your Cargo.toml:

[dependencies]
zod-rs = "0.4"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
FeatureDescription
axumAxum web framework integration
tsTypeScript Zod schema generation
# With Axum integration
zod-rs = { version = "0.4", features = ["axum"] }
# With TypeScript codegen
zod-rs = { version = "0.4", features = ["ts"] }
use serde_json::json;
use zod_rs::prelude::*;
fn main() {
// Define a schema
let user_schema = object()
.field("name", string().min(2).max(50))
.field("email", string().email())
.field("age", number().min(0.0).max(120.0).int());
// Validate data
let user_data = json!({
"name": "Alice",
"email": "alice@example.com",
"age": 25
});
match user_schema.safe_parse(&user_data) {
Ok(validated_data) => println!("Valid: {:?}", validated_data),
Err(errors) => println!("Invalid: {}", errors),
}
}

All schemas support these methods:

let schema = string();
match schema.safe_parse(&json!("hello")) {
Ok(value) => println!("Valid: {}", value),
Err(errors) => println!("Invalid: {}", errors),
}

parse(value) — parse with panic on error

Section titled “parse(value) — parse with panic on error”
let schema = string();
let result = schema.parse(&json!("hello")); // Panics on failure
let schema = string();
let result = schema.validate(&json!("hello"));

For struct-based validation, use the ZodSchema derive macro:

use serde::{Deserialize, Serialize};
use serde_json::json;
use zod_rs::prelude::*;
#[derive(Debug, Serialize, Deserialize, ZodSchema)]
struct User {
#[zod(min_length(3), max_length(20))]
username: String,
#[zod(email)]
email: String,
#[zod(min(13.0), max(120.0), int)]
age: u32,
}
let data = json!({
"username": "alice_dev",
"email": "alice@example.com",
"age": 28
});
let user = User::validate_and_parse(&data).unwrap();

The project is organized as a Cargo workspace:

CrateDescription
zod-rsMain validation library with schema types
zod-rs-macrosDerive macros for ZodSchema
zod-rs-tsTypeScript Zod schema generation
zod-rs-utilUtility functions, error handling, and i18n