Sequelizejs - allowNull的自定义消息

pru*_*ule 5 validation sequelize.js

如果我有模特用户:

var User = sequelize.define('User', {
  name: {
    type: Sequelize.STRING,
    allowNull: false,
    validate: {
      notEmpty: {
        msg: 'not empty'
      }
    }
  },
  nickname: {
    type: Sequelize.STRING
  }
});
Run Code Online (Sandbox Code Playgroud)

如何在name为null或未提供时指定消息?

这段代码:

User.create({}).complete(function (err, user) {
  console.log(err);
  console.log(user);
});
Run Code Online (Sandbox Code Playgroud)

生产:

{ [SequelizeValidationError: Validation error]
  name: 'SequelizeValidationError',
  message: 'Validation error',
  errors: 
   [ { message: 'name cannot be null',
       type: 'notNull Violation',
       path: 'name',
       value: null } ] }
Run Code Online (Sandbox Code Playgroud)

生成消息'name not not null'并且似乎不在我的控制之下.

使用User.create({name:''})向我显示我的自定义消息'not empty':

{ [SequelizeValidationError: Validation error]
  name: 'SequelizeValidationError',
  message: 'Validation error',
  errors: 
   [ { message: 'not empty',
       type: 'Validation error',
       path: 'name',
       value: 'not empty',
       __raw: 'not empty' } ] }
Run Code Online (Sandbox Code Playgroud)

有没有办法为allowNull提供消息?

谢谢

use*_*648 5

遗憾的是,目前尚未实现Null验证错误的自定义消息.根据源代码,notNull不推荐使用验证来支持基于模式的验证,并且模式验证中的代码不允许自定义消息.有一个功能请求,请访问https://github.com/sequelize/sequelize/issues/1500.作为一种解决方法,您可以捕获Sequelize.ValidationError并插入包含您的消息的一些自定义代码.

例如

User.create({}).then(function () { /* ... */ }).catch(Sequelize.ValidationError, function (e) {
    var i;
    for (i = 0; i < e.errors.length; i++) {
      if (e.errors[i].type === 'notNull Violation') {
        // Depending on your structure replace with a reference
        // to the msg within your Model definition
        e.errors[i].message = 'not empty';
      }
    }
})
Run Code Online (Sandbox Code Playgroud)