如何在Yup的test()方法中使用context并校验context选项提供的值?
在Yup的
test()方法中使用Context的指南 嘿,我来帮你理清在Yup的test()方法里怎么使用context,以及如何校验context提供的值~官方文档对when()的说明确实更详细,但test()的用法其实也很灵活,下面给你一步步拆解:
1. 从test()回调中获取Context
Yup的test()方法的回调函数会接收三个参数:当前字段的值、context对象、以及测试配置选项。其中context对象里的context属性,就是你在校验时传入的上下文数据。举个直观的例子:
const schema = yup.object().shape({ password: yup.string().test( 'password-match', '密码必须和确认密码一致', (value, ctx) => { // 从ctx.context中拿到传入的上下文数据 const confirmPassword = ctx.context?.confirmPassword; return value === confirmPassword; } ) }); // 校验时通过第二个参数传入context schema.validate({ password: '123456' }, { context: { confirmPassword: '123456' } }) .then(valid => console.log(valid)) .catch(err => console.log(err.errors));
2. 校验Context提供的值
如果需要校验context里的某个值是否合法,直接在test()回调里对ctx.context的属性做判断即可。比如我们要确保context里的minLength是合法数字,同时当前字段长度不小于这个值:
const schema = yup.string().test( 'min-length-from-context', '字段长度不能小于${minLength}', (value, ctx) => { const minLength = ctx.context?.minLength; // 先校验context中的值是否有效 if (typeof minLength !== 'number' || minLength < 1) { // 用ctx.createError()生成自定义错误,让提示更清晰 return ctx.createError({ message: '上下文的minLength必须是大于0的数字' }); } // 再校验当前字段的值是否符合要求 return value.length >= minLength; } ); // 传入合法context的情况 schema.validate('hello', { context: { minLength: 5 } }) .then(valid => console.log(valid)) // 输出hello .catch(err => console.log(err.errors)); // 传入非法context的情况 schema.validate('hi', { context: { minLength: 'not-a-number' } }) .catch(err => console.log(err.errors)); // 输出["上下文的minLength必须是大于0的数字"]
3. 实用注意事项
- 做空值判断:context可能未被传入,访问
ctx.context的属性时最好用可选链(?.)避免报错。 - 自定义错误:如果context的值不合法,用
ctx.createError()生成错误比直接返回false更友好,能给出针对性提示。 - 与
when()的区别:when()侧重根据context或其他字段动态切换校验规则,而test()是更自由的自定义校验,适合处理复杂的context相关逻辑。
内容的提问来源于stack exchange,提问作者Max Gordon
相关产品推荐
相关产品推荐

