POST method. PATACH and PUT method.module.exports = function(req, res, next) {
/**
* If method is PATCH and PUT
* then edit email and confirmEmail
* and remove password and confirmPassword
*/
if(req.method === 'PATCH' || req.method === 'PUT') {
// how ?
}
let data = req.body;
let err = Joi.validate(data, schema, {abortEarly: false});
if (err && err.error !== null) {
unique= [];
message =[];
err.error.details.forEach(element => {
if(!(element.path in unique )) {
unique[element.path]=1;
message.push(element);
}
});
res.status(422).json({message: message});
res.end();
return false;
}
next();
}
I tried so many ways but did not find the solution for example,
if(req.method === 'PATCH' || req.method === 'PUT') {
schema['email'] = Joi.string().optional().email();
schema['confirmEmail'] = Joi.any().valid(Joi.ref('email')).optional().options({ language: { any: { allowOnly: 'does not match with email' } } });
delete schema['password'];
delete schema ['confirmPassword'];
delete schema ['userType'];
}
Have you tried https://github.com/hapijs/joi/blob/v13.0.2/API.md#anystrip ?
The thing is that I wanna remove before validation. beside I want to edit some key. For example, email field is required on post method, but I want to make it optional on PATCH and PUT method.
keyIDoNotWant: Joi.any().strip()? Joi will delete it and since it is any it won't errorconst schemaForPost = Joi.object({
email: Joi.string().required(),
someotherthing: Joi.string()
});
now .required be removed/overriden from email in subsequent schema
by concatenating like this:
const schemaForPut = schemaForPost.concat(
Joi.object({
email: Joi.string().optional(),
someotherthing: Joi.string()
})
);
that said its probably best to just define 2 different schemas....
I separate my schema for edit, thanks
a method like .without() but that work inverse
or a method like .strip() but that works BEFORE validation, would be great!
i mean something like:
const schema = Joi.object().keys({
a: Joi.any(),
b: Joi.any(),
c: Joi.any(),
}).withOnly('a', 'c');
//resulting in a schema with only a and c
const stripped = Joi.object().keys({
a: Joi.any(),
c: Joi.any(),
})