I'm building an Express API and using @hapi/joi for validation. However I find myself in the following situation: if I want to validate a new user, all the properties in the schema have to be required, but if the client wants to modify a user, these properties must be optional since only the client knows what properties it will modify. So if I have this schema for new users :
function validateUser(user) {
const schema = Joi.object().keys({
name: Joi.string().required(),
lastName: Joi.string().required(),
email: Joi.string().email().required(),
password: Joi.string().required(),
address: Joi.string().required(),
city: Joi.string().required(),
district: Joi.string().required()
});
return schema.validate(user);
}
Since all the properties are required, when I want to use a schema with the same properties but all optional, I have to hard code another schema where all properties are optional. Is there a way or an option of Joi to avoid redundant code? Like an isNew parameter passed to the validateUser function to apply it to the schema?