When trying to validate using the Yup library, the error "branch is not a function" is being thrown in the following function (I have commented out the schema.validate function in that case my code is working but with scheme its not working):
const schema = Yup.object({
boundary: Yup.string().required('Boundary is required'),
boundaryConstructionDate: Yup.string().when('boundary', {
is: (value) => value === 'yes',
then: Yup.string().required('Boundary construction date is required'),
otherwise: Yup.string(),
}),
toilet: Yup.string().required('Toilet is required'),
toiletConstructionDate: Yup.string().when('toilet', {
is: (value) => value === 'yes',
then: Yup.string().required('Toilet construction date is required'),
otherwise: Yup.string(),
}),
payjal: Yup.string().required('Payjal is required'),
ramp: Yup.string().required('Ramp is required'),
rampConstructionDate: Yup.string().when('ramp', {
is: (value) => value === 'yes',
then: Yup.string().required('Ramp construction date is required'),
otherwise: Yup.string(),
}),
divyangToilet: Yup.string().required('DivyangToilet is required'),
divyangToiletConstructionDate: Yup.string().when('divyangToilet', {
is: (value) => value === 'yes',
then: Yup.string().required('DivyangToilet construction date is required'),
otherwise: Yup.string(),
}),
floorTiles: Yup.string().required('Floor Tiles is required'),
floorTilesConstructionDate: Yup.string().when('floorTiles', {
is: (value) => value === 'yes',
then: Yup.string().required('Floor Tiles construction date is required'),
otherwise: Yup.string(),
}),
library: Yup.string().required('Library is required'),
libraryConstructionDate: Yup.string().when('library', {
is: (value) => value === 'yes',
then: Yup.string().required('Library construction date is required'),
otherwise: Yup.string(),
}),
});
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',
});
}
};
Even though there is no function or variable named "branch" in the code, and all the dependencies are imported correctly. Can anyone help me identify the root cause of this error and suggest a possible solution?
Did you recently upgrade yup to v1+? It appears the .when()
api has changed and that error appears if you use the old syntax.
You'd change to use the following syntax:
...
boundaryConstructionDate: Yup.string().when('boundary', {
is: (value) => value === 'yes',
then: (schema) => schema.required('Boundary construction date is required'),
otherwise: (schema) => schema,
})
...
etc.