Reputation: 7054
I want to validate one field and to allow another fields without validation; by example just to validate: "firstname" field. In my code when I comment 'payload', hapi allow me to record any field, when I uncomment 'payload' hapijs dont allow me record any field, but I want just to validate by example 'firstname' to be a 'string' and let rest of fields to allow. I plan to have variable fields accord a database config, so I'm going to just validate some fixed fields and let to save another variable fields controlled in the front end, not in the backend
config: {
validate: {
/* payload: {
firstname: Joi.string(),
lastname: Joi.string()
...anothers fields...
}*/
}
}
UPDATED: thanks to Robert K. Bell, i've adapted the solution is to add 'validate':
config: {
validate: {
options: {
allowUnknown: true
},
payload: {
firstname: Joi.string()
}
}
}
Upvotes: 27
Views: 24798
Reputation: 554
.... {allowUnknown: true}
as per doc, there is "options" method can be used while creating Joi objectSchema.
i.e. tobe very simple UI can send many keys but use only 2 keys email, and password. so a validation function can be defined as this.
function validateUserForSubscription(input) {
const schema = Joi.object({
email: Joi.string().min(5).max(255).required().email(),
password: Joi.string().min(5).max(1024).required()
}).options({ allowUnknown: true });
return schema.validate(input);
}
in other file use it like this.
const isValidUser = validateUserForSubscription(req.body);
Upvotes: 2
Reputation: 467
config: {
validate: {
payload: Joi.object({
'firstname': Joi.string(),
}).options({ allowUnknown: true })
}
}
Instead of adding validation fields in the validate validate the payload directly using Joi object. Which accepts allowUnknown true using this it will only validated only the fields which are mentioned in the Joi Object.
Upvotes: 15
Reputation: 10174
You may be looking for the .unknown()
method:
object.unknown([allow])
Overrides the handling of unknown keys for the scope of the current object only (does not apply to children) where:
allow
- if false
, unknown keys are not allowed, otherwise unknown keys are ignored.js
const schema = Joi.object({ a: Joi.any() }).unknown();
Upvotes: 25