如何针对Sails中的另一个模型属性验证模型属性?

rag*_*lka 5 sails.js

假设我Invoice在SailsJS中有一个模型。它具有2个日期属性:issuedAtdueAt。如何创建自定义验证规则,以检查到期日等于或大于发布日期?

我尝试创建自定义规则,但似乎无法访问规则内的其他属性。

module.exports = {

  schema: true,

  types: {
    duedate: function(dueAt) {
      return dueAt >= this.issuedAt // Doesn't work, "this" refers to the function, not the model instance
    }
  },

  attributes: {

    issuedAt: {
      type: 'date'
    },

    dueAt: {
      type: 'date',
      duedate: true
    }

  }

};
Run Code Online (Sandbox Code Playgroud)

Paw*_*oła 2

模型中的 beforeCreate 方法作为第一个参数采用值。我在这里看到的这种验证的最佳地点。

beforeCreate: (values, next){
  if (values.dueAt >= values.issuedAt) {
      return next({error: ['...']})
  }
  next()
}
Run Code Online (Sandbox Code Playgroud)