使用Yup库验证时报错'branch is not a function'的排查与解决
问题排查:Yup验证时抛出"branch is not a function"错误
根本原因
Yup的when条件验证API要求,then和otherwise选项必须是接收当前字段schema为参数的函数,返回修改后的schema。你当前代码中直接返回了新创建的Yup.string()实例,不符合API要求,导致Yup内部处理分支逻辑时调用branch函数失败,抛出该错误。
解决方案
将所有when配置中的then和otherwise改为函数形式,基于当前字段的原有schema进行修改:
then回调接收schema参数,添加required规则otherwise可以简化为返回原schema(或者直接省略,因为默认行为就是保持原schema)
修正后的代码
const schema = Yup.object({ boundary: Yup.string().required('Boundary is required'), boundaryConstructionDate: Yup.string().when('boundary', { is: (value) => value === 'yes', then: (schema) => schema.required('Boundary construction date is required'), otherwise: (schema) => schema, }), toilet: Yup.string().required('Toilet is required'), toiletConstructionDate: Yup.string().when('toilet', { is: (value) => value === 'yes', then: (schema) => schema.required('Toilet construction date is required'), otherwise: (schema) => schema, }), payjal: Yup.string().required('Payjal is required'), ramp: Yup.string().required('Ramp is required'), rampConstructionDate: Yup.string().when('ramp', { is: (value) => value === 'yes', then: (schema) => schema.required('Ramp construction date is required'), otherwise: (schema) => schema, }), divyangToilet: Yup.string().required('DivyangToilet is required'), divyangToiletConstructionDate: Yup.string().when('divyangToilet', { is: (value) => value === 'yes', then: (schema) => schema.required('DivyangToilet construction date is required'), otherwise: (schema) => schema, }), floorTiles: Yup.string().required('Floor Tiles is required'), floorTilesConstructionDate: Yup.string().when('floorTiles', { is: (value) => value === 'yes', then: (schema) => schema.required('Floor Tiles construction date is required'), otherwise: (schema) => schema, }), library: Yup.string().required('Library is required'), libraryConstructionDate: Yup.string().when('library', { is: (value) => value === 'yes', then: (schema) => schema.required('Library construction date is required'), otherwise: (schema) => schema, }), }); const validateWithYup = () => async (req, res, next) => { try { let object = { boundary: 'no', boundaryConstructionDate: '', toilet: 'no', toiletConstructionDate: '', payjal: 'no', ramp: 'no', rampConstructionDate: '', divyangToilet: 'no', divyangToiletConstructionDate: '', floorTiles: 'no', floorTilesConstructionDate: '', library: 'no', libraryConstructionDate: '' }; await schema.validate(object, { abortEarly: false }); next(); } catch (error) { console.log('ERROR HERE --->', error); return res.status(400).json({ message: 'Validation error', }); } };
内容的提问来源于stack exchange,提问作者Azeez
相关产品推荐
相关产品推荐

