I've been trying to implement the following joi validation.
joiSchema = Joi.object().keys({
taskno: Joi.string().alphanum().required().uppercase().trim(),
taskstatus: Joi.valid('G', 'C', 'I', 'S'),
taskpriority: Joi.number().integer().max(5).min(1),
stuckreason: Joi.string().allow('').max(200).trim(),
dttarget: Joi.date().iso(),
dtdue: Joi.date().iso(),
dtcomplete: Joi.when('taskstatus', {
is: Joi.valid('C', 'I'),
then: Joi.date().iso().required(),
})
});
My object contains taskno, dttarget and dtdue and I only want to validate this.
If i joi.validate()
object it returns error "dtcomplete is required" .
Is there a way to optionally check "dtcomplete"
Try the condition for dtcomplete
along with exist()
in Joi
So the code will be like below
joiSchema = Joi.object().keys({
taskno: Joi.string().alphanum().required().uppercase().trim(),
taskstatus: Joi.valid('G', 'C', 'I', 'S'),
taskpriority: Joi.number().integer().max(5).min(1),
stuckreason: Joi.string().allow('').max(200).trim(),
dttarget: Joi.date().iso(),
dtdue: Joi.date().iso(),
dtcomplete: Joi.when('taskstatus', {
is: Joi.exist().valid('C', 'I'),
then: Joi.date().iso().required(),
})
});
Only the difference is at is: Joi.exist().valid('C', 'I'),
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.