Reputation: 1456
const ValidationSchema = Yup.object().shape({
name: Yup.string()
.min(2, 'String too short!')
.max(50, 'String too long!')
.required('Field is required!')
.lowercase(),
phases: Yup.array().of(
Yup.object().shape({
sla_type: Yup.string(),
sla: Yup.number(),
}),
),
});
First of all I just started to learn YUP and love it. kudos to the team...
Above is my validation schema.
Under Phases
I have two fields: sla_type
and sla
Here is what I am trying to accomplish:
sla_type
is empty, and sla
is also empty no validation required, no values requiredsla_type === 'minutes'
, sla
should be min(1), max(60)sla_type === 'hours'
, sla
should be min(1), max(24)sla_type === 'days'
, sla
should be min(1), max(90)How can I achieve this please?
Upvotes: 2
Views: 85
Reputation: 16726
You can make use of yup.when(), like this:
const ValidationSchema = Yup.object().shape({
name: Yup.string()
.min(2, 'String too short!')
.max(50, 'String too long!')
.required('Field is required!')
.lowercase(),
phases: Yup.array().of(
Yup.object().shape({
sla_type: Yup.string().oneOf(['minutes', 'hours', 'days']),
sla: Yup.number().when('sla_type', (sla_type) => {
switch (sla_type) {
case 'minutes':
return Yup.number().min(1).max(60)
case 'hours':
return Yup.number().min(1).max(24)
case 'days':
return Yup.number().min(1).max(90)
}
})
})
)
});
Upvotes: 1