主题
条件与动态验证
Yup 支持根据其他字段的值动态改变验证规则,常用 when
方法实现条件校验。
导入方式
js
import { object, string, number } from 'yup';
基本用法
js
const schema = object({
isAdult: number().required(),
parentName: string().when('isAdult', {
is: 0,
then: string().required('未成年必须填写父母姓名'),
otherwise: string().notRequired()
})
});
when('otherField', { is, then, otherwise })
- 当
otherField
的值满足is
条件时,应用then
验证规则 - 否则应用
otherwise
规则
使用函数动态生成规则
js
const schema = object({
age: number().required(),
category: string().when('age', (age, schema) => {
if (age < 18) return schema.required().oneOf(['child']);
return schema.required().oneOf(['adult', 'senior']);
})
});
- 第二种形式可以使用回调函数,根据值动态返回不同的 Schema
多字段条件验证
js
const schema = object({
status: string().required(),
reason: string().when(['status', 'age'], (status, age, schema) => {
if (status === 'rejected' && age < 18) {
return schema.required('未成年人被拒绝必须填写原因');
}
return schema.notRequired();
})
});
- 支持多个字段作为条件
小结
when
用于条件验证- 支持单字段或多字段动态规则
- 可返回不同的 Schema,实现灵活验证逻辑