问题 自定义(用户友好)ValidatorError消息


我对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.")

这显然不是理想的解决方案。

我在看 快递形式 和 节点验证 但仍想使用猫鼬验证功能。


3255
2018-01-24 12:09


起源

还有快速验证器,效果很好。 - chovy


答案:


我通常使用辅助函数来处理这类事情。只是嘲笑这个比我使用的更一般。这个人将采用所有“默认”验证器(必需,最小,最大等)并使他们的消息更漂亮(根据 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?


16
2018-03-02 20:21



谢啦 :)。我已经分叉了mongoose项目,并认为解决了这个问题。我寄了 拉请求 愚蠢的人。附:这根本不是CoffeScript ...我只想写一些伪代码,但主持人添加了CoffeScript标签:) - ManInTheBox
真棒谢谢你 - Unitech


如果需要获取第一条错误消息,请参阅以下示例:

var firstError = err.errors[Object.keys(err.errors)[0]];
return res.status(500).send(firstError.message);

此致,Nicholls


0
2017-10-07 15:50