Reputation: 1823
Say I have the following schema
const schema = Joi.object({
title: Joi.string().required(),
start_date: Joi.date().iso().required(),
end_date: Joi.date().iso().greater(Joi.ref('start_date')).required()
});
In one occasion I'd like to validate the entire schema against an object
const obj = {
title: 'abc',
start_date: '2021-11-09',
end_date: '2021-11-10'
}
const validationResult = schema.validate(obj);
And on the other I'd like to validate against part of the schema with my partial object (I don't want to be alarmed about a missing title, for instance)
const obj = {
start_date: '2021-11-09',
end_date: '2021-11-11'
}
const validationResult = schema/*sudo*/.onlyFields(['start_date', 'end_date']).validate(obj);
Is it possible? Workaround is having 2 schemas - titleSchema and dateSchema and concatinating
Upvotes: 2
Views: 768
Reputation: 1823
Solved using the schema.extract
api
function joiSubSchema(base, fields) {
return fields.reduce((schema, field) => {
return schema.concat(Joi.object({
[field]: base.extract(field)
}));
}, Joi.object());
}
Upvotes: 2