我真的是 Mongoose 的新手,所以我想知道是否有一些方法可以设置 custom error message
而不是像 Validator "required" failed for path password
这样的默认值.
我想设置类似 Password is required.
更人性化。
我编写了一些自定义验证器并设置了 type
带有此用户友好错误消息的属性,但我不确定 type
是错误消息的正确占位符。也没有办法在预定义的验证器上设置自定义消息,如 min, max, required, enum...
一种解决方案是每次检查 type
抛出错误的属性并手动分配错误消息,但认为这是验证器的工作:
save model
if error
check error type (eg. "required")
assign fancy error message (eg. "Password is required.")
这显然不是理想的解决方案。
我看了express-form和 node-validator但仍想使用 Mongoose 验证功能。
最佳答案
我通常使用辅助函数来处理这些事情。只是 mock 这个比我使用的更通用一点。这家伙将采用所有“默认”验证器(必需、最小值、最大值等)并使他们的消息更漂亮(根据下面的 messages
对象),并仅提取您传入了您的验证器以进行自定义验证。
function errorHelper(err, cb) {
//If it isn't a mongoose-validation error, just throw it.
if (err.name !== 'ValidationError') return cb(err);
var messages = {
'required': "%s is required.",
'min': "%s below minimum.",
'max': "%s above maximum.",
'enum': "%s not an allowed value."
};
//A validationerror can contain more than one error.
var errors = [];
//Loop over the errors object of the Validation Error
Object.keys(err.errors).forEach(function (field) {
var eObj = err.errors[field];
//If we don't have a message for `type`, just push the error through
if (!messages.hasOwnProperty(eObj.type)) errors.push(eObj.type);
//Otherwise, use util.format to format the message, and passing the path
else errors.push(require('util').format(messages[eObj.type], eObj.path));
});
return cb(errors);
}
而且可以这样使用(快速路由器示例):
function (req, res, next) {
//generate `user` here
user.save(function (err) {
//If we have an error, call the helper, return, and pass it `next`
//to pass the "user-friendly" errors to
if (err) return errorHelper(err, next);
}
}
之前:
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ username:
{ message: 'Validator "required" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'required' },
state:
{ message: 'Validator "enum" failed for path state',
name: 'ValidatorError',
path: 'state',
type: 'enum' },
email:
{ message: 'Validator "custom validator here" failed for path email',
name: 'ValidatorError',
path: 'email',
type: 'custom validator here' },
age:
{ message: 'Validator "min" failed for path age',
name: 'ValidatorError',
path: 'age',
type: 'min' } } }
之后:
[ 'username is required.',
'state not an allowed value.',
'custom validator here',
'age below minimum.' ]
编辑:Snap,刚刚意识到这是一个 CoffeeScript 问题。不是 CoffeeScript 人,我真的不想用 CS 重写它。您总是可以将其作为 js
文件添加到您的 CS 中?
关于node.js - 自定义(用户友好)ValidatorError 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8986556/