mcpField
Y
yup

yup

github.com/claude-dev-suite开发4650 次安装2 天前更新
代码仓库

关于 yup

面向 JavaScript 和 TypeScript 开发者的 Yup 速查技能,介绍常见验证模式、验证选项及表单相关用法。

主要功能

  1. 01字符串、数字、日期、数组和对象模式
  2. 02同步与异步验证
  3. 03使用 InferType 推断类型
  4. 04剔除未知字段并进行类型转换

适用场景

  1. 01验证用户及表单数据
  2. 02收集多条验证错误
  3. 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

特性YupZod
类型推断良好出色
包体积~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