Reputation: 75
I'm currently trying to setup validation using the joi package but I'm running into some issues that most likely revolve around syntax.
The schema I've set up is a fairly simple one that checks whether or not a number is valid and/or if the id exists within the database.
export default router.post('/', async function(req, res, next) {
const Joi = require('joi');
// for testing
if (!Object.keys(req.body).length) {
req.body = {'tId':'123456789'}
}
const data = req.body;
const schema = Joi.object().keys({
tId: Joi.string.tId.required()
});
Joi.validate(data, schema, (err, value) => {
if(err){
res.status(404).json({
status: 'error',
message: 'tId not found',
data: data
});
} else {
res.json({
status: 'success',
message: 'Person found',
data: Object.assign(22, value)
});
}
});
})
The error that I'm currently getting is around tId: Joi.string.tId.required()
.
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'required' of undefined
My current research has been primarily around the following link:
https://www.digitalocean.com/community/tutorials/how-to-use-joi-for-node-api-schema-validation
I tried to mimic the concepts that this tutorial implemented and I think I have somewhat of a decent idea how it works but I'm just having some trouble with the syntax of the library.
Any links, videos, projects etc that makes good use of the joi library would be extremely helpful.
Upvotes: 0
Views: 2063
Reputation: 343
As you guessed, it's just a syntax error. Update this part:
const schema = Joi.object().keys({
tId: Joi.string().required()
});
From Joi.validate
, I'm assuming you're Joi v15 or lower, here's the documentation you're looking for-
https://joi.dev/api/?v=15.1.1#string---inherits-from-any
Upvotes: 1