Sequelize:如果当前验证器失败,如何防止执行以下验证器

时间:2016-06-21 14:42:08

标签: validation sequelize.js

我在模型中有一个带有一些验证器的字段:

...
someField: {
  ...
  validate: {
      someValidator1: true,
      someValidator2: true,
  }
}, 
...

Sequelize 中的两个验证器都是独立执行的。

如果第一个失败,如何不执行第二个?

1 个答案:

答案 0 :(得分:1)

一旦抛出错误,脚本执行就会停止。

http://docs.sequelizejs.com/en/latest/docs/models-definition/,Sequelize.js的作者给出了这个例子:

var ValidateMe = sequelize.define('foo', {
  foo: {
    type: Sequelize.STRING,
    validate: {
      // custom validations are also possible:
      isEven: function(value) {
        if(parseInt(value) % 2 != 0) {
          // This error will stop code execution and give you the chance to catch and handle the error
          throw new Error('Only even values are allowed!')
        // we also are in the model's context here, so this.otherField
        // would get the value of otherField if it existed
        }
      }
    }
  }
});