关于 yup
面向 JavaScript 和 TypeScript 开发者的 Yup 速查技能,介绍常见验证模式、验证选项及表单相关用法。
主要功能
- 01字符串、数字、日期、数组和对象模式
- 02同步与异步验证
- 03使用 InferType 推断类型
- 04剔除未知字段并进行类型转换
适用场景
- 01验证用户及表单数据
- 02收集多条验证错误
- 03从模式推断 TypeScript 类型
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ claude-dev-suite/ claude-dev-suite --skill yup安装后在 Claude Code 中输入/yup确认已加载。
附带文件advanced.md
详细介绍
Yup - 快速参考
完整参考:有关条件验证(.when)、自定义验证(.test)、Formik/React Hook Form 集成、转换和本地化,请参阅 advanced.md。
深入了解:使用
mcp__documentation__fetch_docs,并将 technology 设置为:yup,以获取完整文档。
设置
npm install yup
基本用法
import * as yup from 'yup';
const userSchema = yup.object({
name: yup.string().required().min(2).max(50),
email: yup.string().required().email(),
age: yup.number().required().min(18).max(120).integer(),
bio: yup.string().optional(),
});
// Type inference
type User = yup.InferType<typeof userSchema>;
// Validate
async function validateUser(data: unknown) {
try {
const user = await userSchema.validate(data, { abortEarly: false });
return { success: true, data: user };
} catch (error) {
if (error instanceof yup.ValidationError) {
return { success: false, errors: error.errors };
}
throw error;
}
}
架构类型
字符串
const stringSchema = yup
.string()
.required('Name is required')
.min(2, 'Too short')
.max(100, 'Too long')
.trim()
.email('Invalid email')
.url('Invalid URL')
.matches(/^[a-zA-Z]+$/, 'Only letters allowed')
.oneOf(['option1', 'option2'], 'Must be one of the options');
数字
const numberSchema = yup
.number()
.required()
.min(0)
.max(100)
.positive()
.integer()
.typeError('Must be a number');
日期
const dateSchema = yup
.date()
.required()
.min(new Date('2020-01-01'), 'Too old')
.max(new Date(), 'Cannot be in future');
数组
const arraySchema = yup
.array()
.of(yup.string().required())
.required()
.min(1, 'At least one item')
.max(10, 'Maximum 10 items')
.ensure(); // Transform null/undefined to []
对象
const objectSchema = yup.object({
name: yup.string().required(),
address: yup.object({
street: yup.string().required(),
city: yup.string().required(),
}),
}).noUnknown(true); // Strip unknown keys
// Partial object (all fields optional)
const partialSchema = objectSchema.partial();
验证选项
const result = await schema.validate(data, {
abortEarly: false, // Return all errors, not just first
stripUnknown: true, // Remove unknown keys
strict: false, // Allow type coercion
});
// Sync validation
schema.validateSync(data);
schema.isValidSync(data); // Returns boolean
对比:Yup 与 Zod
| 特性 | Yup | Zod |
|---|---|---|
| 类型推断 | 良好 | 出色 |
| 包体积 | ~12KB | ~8KB |
| 异步验证 | 内置 | .parseAsync() |
| Formik | 原生支持 | 通过 resolver |
| 条件验证 | .when() | .refine() |
不适合使用此技能的情况
- 新项目 - 建议使用 Zod,以获得更好的 TypeScript 集成
- NestJS 应用程序 - 使用带装饰器的
class-validator - 非表单验证 - Zod 为通用验证提供了更好的 API
反模式
| 反模式 | 不良之处 | 正确做法 |
|---|---|---|
| 在组件中定义架构 | 每次渲染都会重新创建 | 在模块级别定义 |
| 忘记设置 abortEarly: false | 只显示第一个错误 | 设置 abortEarly: false |
| 不提供自定义消息 | 错误信息通用 | 为每项添加自定义消息 |
| 不使用 InferType | 手动定义类型 | 使用 yup.InferType |
快速故障排除
| 问题 | 原因 | 解决方案 |
|---|---|---|
| InferType 类型错误 | 缺少导入 | 从 'yup' 导入类型 |
| 异步验证不起作用 | 使用了 validateSync | 使用 .validate()(异步) |
| 意外出现“Value is required” | Undefined 与 null 的区别 | 使用 .nullable() 或 .optional() |
| 未显示错误消息 | abortEarly: true | 设置 abortEarly: false |
生产环境检查清单
- 在模块级别定义架构
- 使用 InferType 进行类型推断
- 自定义错误消息
- 表单设置 abortEarly: false
- 为表单库配置 resolver
- 多语言场景下启用本地化
参考文档
评论
支持 Markdown