Skip to content

String

Create a string schema with string().

use zod_rs::prelude::*;
use serde_json::json;
let schema = string();
assert!(schema.safe_parse(&json!("hello")).is_ok());
assert!(schema.safe_parse(&json!(42)).is_err());
let schema = string().min(3);
assert!(schema.safe_parse(&json!("hello")).is_ok());
assert!(schema.safe_parse(&json!("hi")).is_err());
let schema = string().max(10);
assert!(schema.safe_parse(&json!("hello")).is_ok());
let schema = string().length(5);
assert!(schema.safe_parse(&json!("hello")).is_ok());
assert!(schema.safe_parse(&json!("hi")).is_err());
let schema = string().email();
assert!(schema.safe_parse(&json!("user@example.com")).is_ok());
assert!(schema.safe_parse(&json!("not-an-email")).is_err());
let schema = string().url();
assert!(schema.safe_parse(&json!("https://example.com")).is_ok());
let schema = string().regex(r"^[a-zA-Z]+$");
assert!(schema.safe_parse(&json!("hello")).is_ok());
assert!(schema.safe_parse(&json!("hello123")).is_err());
let schema = string().starts_with("hello");
assert!(schema.safe_parse(&json!("hello world")).is_ok());
let schema = string().ends_with("world");
assert!(schema.safe_parse(&json!("hello world")).is_ok());
let schema = string().includes("world");
assert!(schema.safe_parse(&json!("hello world")).is_ok());

Validations can be chained together:

let schema = string()
.min(3)
.max(50)
.email();
#[derive(ZodSchema)]
struct User {
#[zod(min_length(3), max_length(20), regex(r"^[a-zA-Z0-9_]+$"))]
username: String,
#[zod(email)]
email: String,
}