Yup验证类型报错及API错误信息展示问题求助
Yup验证问题排查与服务器错误提示实现方案
一、初始验证错误:提示“必须是object类型,但最终值为null”
问题根源:你的mySchema['add-record']是对象类型Schema(通过yup.object().shape()定义),但调用validate时传入的是单个字段值props.formRef.current.getValues("myId")(字符串"123456789"),而非整个表单对象。
Yup会尝试将传入的字符串转换为对象类型,转换失败后得到null,因此抛出该错误。
解决办法:
- 验证整个表单:传入完整的表单对象
await mySchema['add-record'].validate(props.formRef.current.getValues(), { context: { other: 4 } }); - 仅验证单个字段
myId:直接使用字段对应的Schemaawait mySchema['add-record'].fields.myId.validate(props.formRef.current.getValues("myId"), { context: { other: 4 } });
二、实现服务器错误信息展示
1. when方法失效原因
你的写法存在两个问题:
when的回调必须返回Schema实例,不能直接调用context.createError,否则无法修改验证规则;- 直接引用
context错误,需通过回调参数或this访问上下文。
2. test方法报错原因
- 变量名大小写不匹配:上下文里定义的是
isMyIdServiceError,代码里写成了ismyIdServiceError; - 错误消息模板
'${$MyIdServiceErrorMsg}'不符合Yup语法,无法直接引用上下文变量; - 无需使用
async,此处无异步操作。
正确实现代码
方案一:使用test方法(推荐)
'myId': yup .string() .nullable() .required() .test( 'api-error', '', // 预留空消息,后续通过createError自定义 function(value) { const { isMyIdServiceError, MyIdServiceErrorMsg } = this.options.context; if (isMyIdServiceError) { return this.createError({ path: 'myId', message: MyIdServiceErrorMsg }); } return true; } )
方案二:使用when方法
'myId': yup .string() .nullable() .required() .when('$isMyIdServiceError', { is: true, then: schema => schema.test( 'api-error', '', function() { return this.createError({ path: 'myId', message: this.options.context.MyIdServiceErrorMsg }); } ) })
调用验证时,确保上下文正确传入参数:
await mySchema['add-record'].validate(/* 表单对象或字段值 */, { context: { isMyIdServiceError: true, MyIdServiceErrorMsg: "服务器返回的错误信息" } });
内容的提问来源于stack exchange,提问作者copenndthagen
相关产品推荐
相关产品推荐

