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()
}
}
}
The first input type that joi can validate is path parameters. Consider the following: server. route({ method: 'GET', path: '/hello/{name}', handler: function (request, h) { return `Hello ${request.params.name}!`; }, options: { validate: { params: Joi.
Hapi Joi is an object schema description language and validator for JavaScript objects. With Hapi Joi, we create blueprints or schemas for JavaScript objects (an object that stores information) to ensure validation of key information.
Joi can be used for creating schemas (just like we use mongoose for creating NoSQL schemas) and you can use it with plain Javascript objects. It's like a plug n play library and is easy to use. On the other hand, express-validator uses validator. js to validate expressjs routes, and it's mainly built for express.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With