使用Sequelize自定义验证可能会出现多个验证错误吗?

时间:2017-12-15 19:05:35

标签: node.js validation sequelize.js

Toolbar

这是我的模型定义。问题是如果private Register mRegister; public Controller() { this.mRegister = new Register(this); } @FXML private void initialize() { mRegister.importFrom(new File("prices.txt")); } deliverableSchedule: { type: DataTypes.STRING(64), validate: { isIn: { args: ['onetime', 'recurrent'], msg: 'Must be one of "onetime", "recurrent"' }, isRecurrent(value) { if (value === 'recurrent' && !this.recurrenceInterval) { throw new Error('recurrenceInterval must be set if deliverableSchedule is "recurrent"') } if (value === 'recurrent' && !(this.recurrenceCount > 0)) { throw new Error('recurrenceCount must be greater than 0') } } } }, 并且缺少deliverableSchedulerecurrent

,我希望返回两个错误

1 个答案:

答案 0 :(得分:4)

您可以创建自定义错误

class CustomError extends Error {

    constructor(message, errors) {

        super(message);

        this._errors = errors

    }

    get errors() {

        return this._errors;

    }

}

module.exports = CustomError;

然后

 var CustomError= require('./CustomError')


  deliverableSchedule: {
    type: DataTypes.STRING(64),
    validate: {
      isIn: {
        args: ['onetime', 'recurrent'],
        msg: 'Must be one of "onetime", "recurrent"'
      },
      isRecurrent(value) {
        var errroList = [];
        if (value === 'recurrent' && !this.recurrenceInterval) {
          errroList.push('recurrenceInterval must be set if deliverableSchedule is "recurrent"')
        }

        if (value === 'recurrent' && !(this.recurrenceCount > 0)) {
           errroList.push('recurrenceCount must be greater than 0')
        }

        if (errroList.length > 0) {
            throw new CustomError('Is recurrent error. See errors prop for error list', errroList);
        }
      }
    }
  },