【问题标题】:How to have custom message in JOI Validation如何在 JOI 验证中自定义消息
【发布时间】:2019-03-21 15:21:05
【问题描述】:
我是 NodeJS 新手,需要帮助。我使用 JOI 作为模式验证,我需要为每个验证提供自定义消息。就像如果 min(3) 在那里,我想要自定义消息,如果需要相同的字段,那么我想要不同的自定义消息。
请建议链接到我可以实现此目的的任何示例。以下是我正在尝试的。
const schema = {
name: Joi.string().min(3).error((error) => "Min 3 Characters").required().error((error) => "Field is required")
};
【问题讨论】:
标签:
node.js
validation
schema
joi
【解决方案1】:
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');
});
【解决方案2】:
根据documentation,您可以这样做:
const schema = Joi.string().error(new Error('Was REALLY expecting a string'));
schema.validate(3); // returns Error('Was REALLY expecting a string')
【解决方案3】:
你可以这样做:
const schema = {
name: Joi.string()
.min(3)
.required()
.options({
language: {
any: { required: 'is required' },
string: { min: 'must be at least 3 Characters' },
},
}),
}
【解决方案4】:
在验证结束时添加错误。
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'))
..
});
如果您探索错误函数,您还可以做更多的事情
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();
})