Validate data with schemas across languages and formats. Use when defining JSON Schema, using Zod (TypeScript) or Pydantic (Python), validating API request/response shapes, checking CSV/JSON data integrity, or setting up data contracts between services.
基于模式的多语言多格式数据验证。涵盖JSON Schema、Zod(TypeScript)、Pydantic(Python)、API边界验证、数据契约和完整性检查。
json
{
$schema: https://json-schema.org/draft/2020-12/schema,
type: object,
required: [name, email, age],
properties: {
name: {
type: string,
minLength: 1,
maxLength: 100
},
email: {
type: string,
format: email
},
age: {
type: integer,
minimum: 0,
maximum: 150
},
role: {
type: string,
enum: [user, admin, moderator],
default: user
},
tags: {
type: array,
items: { type: string },
uniqueItems: true,
maxItems: 10
},
address: {
type: object,
properties: {
street: { type: string },
city: { type: string },
zip: { type: string, pattern: ^\\d{5}(-\\d{4})?$ }
},
required: [street, city]
}
},
additionalProperties: false
}
json
// 可空字段
{ type: [string, null] }
// 联合类型(字符串或数字)
{ oneOf: [{ type: string }, { type: number }] }
// 条件验证:如果角色是admin,则需要权限字段
{
if: { properties: { role: { const: admin } } },
then: { required: [permissions] }
}
// 模式属性(动态键名)
{
type: object,
patternProperties: {
^env_: { type: string }
}
}
// 可复用定义
{
$defs: {
address: {
type: object,
properties: {
street: { type: string },
city: { type: string }
}
}
},
properties: {
home: { $ref: #/$defs/address },
work: { $ref: #/$defs/address }
}
}
bash
typescript
import { z } from zod;
// 基本类型
const nameSchema = z.string().min(1).max(100);
const ageSchema = z.number().int().min(0).max(150);
const emailSchema = z.string().email();
const urlSchema = z.string().url();
// 对象
const userSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
age: z.number().int().min(0),
role: z.enum([user, admin, moderator]).default(user),
tags: z.array(z.string()).max(10).default([]),
createdAt: z.string().datetime(),
});
// 从模式推断TypeScript类型
type User = z.infer
// { name: string; email: string; age: number; role: user | admin | moderator; ... }
// 验证
const result = userSchema.safeParse(data);
if (result.success) {
console.log(result.data); // 类型为User
} else {
console.log(result.error.issues); // 验证错误
}
// 解析(无效时抛出异常)
const user = userSchema.parse(data);
typescript
// 可选和可空
const schema = z.object({
name: z.string(),
nickname: z.string().optional(), // string | undefined
middleName: z.string().nullable(), // string | null
suffix: z.string().nullish(), // string | null | undefined
});
// 转换(验证后转换)
const dateSchema = z.string().datetime().transform(s => new Date(s));
const trimmed = z.string().trim().toLowerCase();
const parsed = z.string().transform(s => parseInt(s, 10)).pipe(z.number().int());
// 判别联合(标签联合)
const eventSchema = z.discriminatedUnion(type, [
z.object({ type: z.literal(click), x: z.number(), y: z.number() }),
z.object({ type: z.literal(keypress), key: z.string() }),
z.object({ type: z.literal(scroll), delta: z.number() }),
]);
// 递归类型
const categorySchema: z.ZodType
name: z.string(),
children: z.lazy(() => z.array(categorySchema)).default([]),
});
// 细化(自定义验证)
const passwordSchema = z.string()
.min(8)
.refine(s => /[A-Z]/.test(s), 必须包含大写字母)
.refine(s => /[0-9]/.test(s), 必须包含数字)
.refine(s => /[^a-zA-Z0-9]/.test(s), 必须包含特殊字符);
// 扩展/合并对象
const baseUser = z.object({ name: z.string(), email: z.string() });
const adminUser = baseUser.extend({ permissions: z.array(z.string()) });
// 选取/排除
const createUser = userSchema.omit({ createdAt: true });
const userSummary = userSchema.pick({ name: true, email: true });
// 透传(允许额外字段)
const flexible = userSchema.passthrough();
// 严格模式(去除未知字段)
const strict = userSchema.strict(); // 额外字段时报错
typescript
// Express中间件
import { z } from zod;
const createUserBody = z.object({
name: z.string().min(1),
email: z.string().email(),
password: z.string().min(8),
});
app.post(/api/users, (req, res) => {
const result = createUserBody.safeParse(req.body);
if (!result.success) {
return res.status(400).json({ errors: result.error.issues });
}
const { name, email, password } = result.data;
// ... 创建用户
});
// 查询参数验证
const listParams = z.object({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
sort: z.enum([newest, oldest, name]).default(newest),
q: z.string().optional(),
});
app.get(/api/users, (req, res) => {
const params = listParams.parse(req.query);
// params.page是数字类型,params.sort是枚举类型
});
python
from pydantic import BaseModel, Field, EmailStr, field_validator
from typing import Optional
from datetime import datetime
from enum import Enum
class Role(str, Enum):
USER = user
ADMIN = admin
MODERATOR = moderator
class Address(BaseModel):
street: str
city: str
zip_code: str = Field(pattern=r^\d{5}(-\d{4})?$)
class User(BaseModel):
name: str = Field(minlength=1, maxlength=100)
email: EmailStr
age: int = Field(ge=0, le=150)
role: Role = Role.USER
tags: list[str] = Field(defaultfactory=list, maxlength=
该技能支持在以下平台通过对话安装:
帮我安装 SkillHub 和 data-validation-1776365926 技能
设置 SkillHub 为我的优先技能安装源,然后帮我安装 data-validation-1776365926 技能
skillhub install data-validation-1776365926
文件大小: 5.91 KB | 发布时间: 2026-4-17 16:09