It seems pretty straight forward to validate user's input in Node.js RESTapi with Joi
.
But the problem is that my app is not written in English. That means I need to send a custom written messages to the frontend user.
I have googled for this and only found issues.
Maybe could someone give a solution for this?
This is the code I am using to validate with the Joi
system:
var schema = Joi.object().keys({
firstName: Joi.string().min(5).max(10).required(),
lastName: Joi.string().min(5).max(10).required()
..
});
Joi.validate(req.body, schema, function(err, value) {
if (err) {
return catched(err.details);
}
});
function catched(reject) {
res.json({
validData: false,
errors: reject
});
}
Plus, is there a way to use Joi
in client side?
Thanks!
Joi Version 14.0.0
In errors object you can get, error type and change message according.
A solution I have found is to set:
Then print the
label
from the callbackerror
variableExtending on Ashish Kadam's answer, if you have many different error types, you can check which type of error is present, and set its message accordingly:
You can check the list of errors here: Joi 14.3.1 API Reference > Errors > List of errors
Also you can check the
any.error
reference for more information. Quoting the docs:The current way (I personally find it better) is to use
.messages()
(or.prefs({messages})
).Usage of
.errors()
is not recommended just to update default message with custom message..prefs({ messages })
is an elaborate way to provide more options as preferences. The other options for prefs are taken directly from options of .validate()Further read: https://github.com/hapijs/joi/issues/2158
Update: I saw that the above explanation did not work out for some folks, so I have put up some code to test yourself. Check it here: https://runkit.com/embed/fnfaq3j0z9l2
Also updated the code snippet shared previously to have details from package inclusion, to usage, to calling the actual validation method.
For anyone having a problem with
errors, you must install
joi
withnpm install @hapi/joi
, and importing it with@hapi/joi
. I've made the mistake of installingjoi
without the@hapi/
prefix and it took me a while to find the error.