I'm facing a problem when i'm trying to validate a nested schema with Yup().
My cenary is, i have the following payload (that may not always contain maxAge and maxAge, but at least one of them):
{
name: 'userName',
calc: [{
maxAge:{
day:'0',
month:'0',
year:'5',
},
minAge:{
day:'12',
month:'12',
year:'4',
}
}],
}
The problem is, that maxAge and minAge are "optional" but at least one is required, so as the content inside (day,month, year) are both optional, but if one maxAge or minAge is passed, so at least one of the internal content is required.
I've tried the following code:
const Yup = require('yup');
(async () => {
try {
const schema = Yup.object().shape({
name: Yup.string()
.required()
.trim()
.min(2, `Name must have at least 3 characters`)
.max(50, `Name must have at maximum 50 characters`)
.matches(/^[A-Za-zÀ-ÿ\- &]*$/, 'Name is not valid')
.required(),
calc: Yup.array().of(
Yup.object()
.shape(
{
maxAge: Yup.object()
.shape({
year: Yup.string().optional(),
month: Yup.string().optional(),
days: Yup.string().optional()
}).when('minAge', {
is: '' || undefined || {} || null,
then: Yup.object().shape({
year: Yup.string(),
month: Yup.string(),
days: Yup.string()
}).required('This minAge is required.'),
otherwise: Yup.object()
}),
minAge: Yup.object()
.shape({
year: Yup.string().optional(),
month: Yup.string().optional(),
days: Yup.string().optional()
}).when('maxAge', {
is: '' || undefined || {} || null,
then: Yup.object().shape({
year: Yup.string(),
month: Yup.string(),
days: Yup.string()
}).required('This minAge is required.'),
otherwise: Yup.object()
}),
},
[['minAge', 'maxAge']]
)
.required(),
)
});
let test = await schema.validate(
{
name: 'Jonas',
calc: [{
}],
},
{ abortEarly: false }
);
console.log(JSON.stringify(test));
} catch (err) {
console.log(err);
}
})();