[英]Joi validate specific fields based on larger schema
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
解决方法是有 2 个模式 - titleSchema 和 dateSchema 并连接
Solved using the schema.extract
api使用
schema.extract
api 解决
function joiSubSchema(base, fields) {
return fields.reduce((schema, field) => {
return schema.concat(Joi.object({
[field]: base.extract(field)
}));
}, Joi.object());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.