我是NodeJS的新手,需要帮助。我将JOI用作模式验证,并且每次验证都需要自定义消息。就像如果min(3)在那里,我想要自定义消息,并且如果需要相同的字段,那么我想要不同的自定义消息。
请建议链接到我可以实现此目标的任何示例。以下是我正在尝试的方法。
const schema = {
name: Joi.string().min(3).error((error) => "Min 3 Characters").required().error((error) => "Field is required")
};
答案 0 :(得分:0)
add error to the end of your validation.
var schema = Joi.object().keys({
firstName: Joi.string().min(5).max(10).required().error(new Error('Give your error message here for first name')),
lastName: Joi.string().min(5).max(10).required().error(new Error('Give your error message here for last name'))
..
});
there is also more stuff you can do if you explore the error function
firstname: Joi.string()
.max(30)
.min(5)
.required()
.label('First Name')
.error((err) => {
const errs = err.map(x => `${x.flags.label} ${x.type}(${x.context.limit}) with value ${x.context.value}`);
console.log(errs);
return errs.toString();
})
答案 1 :(得分:0)
您可以这样做:
const schema = {
name: Joi.string()
.min(3)
.required()
.options({
language: {
any: { required: 'is required' },
string: { min: 'must be at least 3 Characters' },
},
}),
}
答案 2 :(得分:0)
根据documentation,您可以执行以下操作:
const schema = Joi.string().error(new Error('Was REALLY expecting a string'));
schema.validate(3); // returns Error('Was REALLY expecting a string')
答案 3 :(得分:0)
0
我发现的最佳解决方案是:
创建用于JOI验证的中间件
Validator.js-您可以创建自定义错误对象
const Joi = require('Joi');
module.exports = schema => (req, res, next) => {
const result = Joi.validate(req.body, schema);
if (result.error) {
return res.status(422).json({
errorCause: result.error.name,
missingParams: result.error.details[0].path,
message: result.error.details[0].message
});
}
next();
};
在路由或控制器中传递此中间件功能
const joiValidator = require('../utils/validator'); // Wherever you have declare the validator or middlerware
const userSchema = joi.object().keys({
email : joi.string().email().required(),
password : joi.string().required()
});
routes.routes('/').get(joiValidator(userSchema), (req, res) => {
res.status(200).send('Person Check');
});