Yup条件校验:id为phase时才校验对象的fields数组字段
Yup条件校验规则修正方案
待校验数据结构
{ "values": [ { "id": "Card ID", "checkBox": true, "csvField": "" }, { "id": "title", "checkBox": false, "csvField": "" }, { "id": "subtitle", "checkBox": false, "csvField": "" }, { "id": "phase", "checkBox": false, "csvField": "", "fields": [ { "id": "61d5bc37b995d200116bc73c", "phaseInCsv": "" }, { "id": "61d5c43759bd07001134076a", "phaseInCsv": "" }, { "id": "6203f08dc0eb7000120052a1", "phaseInCsv": "" } ] } ] }
校验需求
- 仅当
values数组下元素的id字段值等于phase时,才对该元素下的fields数组执行必填校验 - 原有编写的校验规则未生效,需要修正
原有未生效代码
const validationSchema = Yup.object().shape({ values: Yup.array().of( Yup.object().shape({ id: Yup.string(), checkBox: Yup.boolean(), csvField: Yup.string().when('checkBox', { is: true, then: Yup.string().required( t('IMPORT.VALIDATION_ERROR.CSV_FIELD_MISSING') ), }), fields: Yup.array().when('id', { is: FormFieldType.PHASE, then: Yup.array() .of( Yup.object().shape({ id: Yup.string(), phaseInCsv: Yup.string().required( t('IMPORT.VALIDATION_ERROR.CSV_FIELD_MISSING') ), }) ) .required(), }), }) ), })
失效原因
原有规则存在两个核心问题:
- 缺少
otherwise分支声明:当id值不等于phase时,Yup没有拿到fields字段的明确校验规则,会导致条件判断逻辑不生效,非目标元素也会被强制校验 - 未做枚举值匹配确认:需要确认
FormFieldType.PHASE的实际值为字符串"phase",枚举值不匹配会直接导致条件永远无法触发
修正后代码
const validationSchema = Yup.object().shape({ values: Yup.array().of( Yup.object().shape({ id: Yup.string(), checkBox: Yup.boolean(), csvField: Yup.string().when('checkBox', { is: true, then: Yup.string().required( t('IMPORT.VALIDATION_ERROR.CSV_FIELD_MISSING') ), otherwise: Yup.string().notRequired() }), fields: Yup.array().when('id', { is: FormFieldType.PHASE, then: Yup.array() .of( Yup.object().shape({ id: Yup.string().required(), phaseInCsv: Yup.string().required( t('IMPORT.VALIDATION_ERROR.CSV_FIELD_MISSING') ), }) ) .required(t('IMPORT.VALIDATION_ERROR.CSV_FIELD_MISSING')), // 核心补充:非phase类型元素的fields字段不做强制校验 otherwise: Yup.array().notRequired() }), }) ), })
补充说明:如果非phase类型的元素对象本身不存在
fields字段,可以在otherwise分支中使用Yup.strip()将该字段从校验结果中移除,避免多余字段干扰校验逻辑。
内容的提问来源于stack exchange,提问作者Abadlia Ramy
相关产品推荐
相关产品推荐

