I am using joi for schema validation. I have created a joi schema object for create operation and everything is working fine. In case of update, I will not get all the fields request body. For that case, I have to write another schema. Is there any way to handle the both create and update with the single schema?
I usually use presence
option during schema validation like
const Joi = require('joi');
function validateUser(data, presence) {
const schema = Joi.object({
name: Joi.string().max(50),
email: Joi.string().email(),
password: Joi.string().min(6).max(30),
});
// use presence option during validation
schema.validate(data, { presence });
}
// in create
validateUser(data, 'required');
// in update
validateUser(data, 'optional');
If required you may use presence() function during schema defining
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.