使用Yup实现:当industryName含'other'时industryNameOther必填的校验问题
Yup表单校验逻辑错误排查与修复
问题场景
你需要实现的校验逻辑是:当字符串数组字段industryName包含'other'时,industryNameOther字段不能为空,但当前编写的校验代码未正常生效。
错误原因分析
你的代码存在三个关键问题:
- 数组类型安全判断缺失:未明确判断
industryName是否为数组,若字段值为undefined或非数组类型,调用includes方法会直接报错; - 不必要的Schema重复创建:在
then分支里重新调用Yup.string()会覆盖原有的Schema配置,直接基于现有Schema添加规则即可; - 路径引用冗余:
when方法的第一个参数用数组包裹industryName属于冗余写法,单个字段直接传字符串即可。
修正后的校验代码
将industryNameOther的校验规则修改为如下形式:
industryNameOther: Yup.string().when('industryName', { is: (industryName) => Array.isArray(industryName) && industryName.includes('other'), then: (schema) => schema.required('helperText.customer.industryNameOther.required'), }),
关键修改点
- 添加
Array.isArray(industryName)判断,确保字段是数组类型后再调用includes,避免运行时错误; then分支接收原schema作为参数,直接链式调用required规则,避免重新创建Schema覆盖原有配置;- 简化
when的字段引用方式,直接传递字段名industryName(因两个字段同属customer对象,相对路径可直接识别)。
完整修正后的Validation Schema
import * as Yup from 'yup'; const validationSchema = Yup.object({ sales: Yup.object({ contactPerson: Yup.string().required('helperText.sales.contactPerson.required'), }), customer: Yup.object({ name: Yup.string().required('helperText.customer.name.required'), sapNumber: Yup.string() .matches(/^4\d{7}$/, 'helperText.customer.sapNumber.format') .notRequired(), address: Yup.string().required('helperText.customer.address.required'), contactPersonMail: Yup.string() .email('helperText.customer.contactPersonMail.format') .notRequired(), industryName: Yup.array().min(1, 'helperText.customer.industryName.number'), industryNameOther: Yup.string().when('industryName', { is: (industryName) => Array.isArray(industryName) && industryName.includes('other'), then: (schema) => schema.required('helperText.customer.industryNameOther.required'), }), relations: Yup.number().required('helperText.customer.relations.number').min(0, 'helperText.customer.relations.number') }), project: Yup.object({ supplyChainParts: Yup.array().required('helperText.project.supplyChainParts.number').min(1, 'helperText.project.supplyChainParts.number'), investmentLocation: Yup.string().required('helperText.project.investmentLocation.required'), investmentType: Yup.string().required('helperText.project.investmentType.required') }) }) export default validationSchema
内容的提问来源于stack exchange,提问作者Paweł Stępień
相关产品推荐
相关产品推荐

