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

时间:2013-10-17 07:41:50

标签: sails.js

我们假设我在SailsJS中有一个Invoice模型。它有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
    }

  }

};

2 个答案:

答案 0 :(得分:1)

模型中的

beforeCreate方法作为第一个参数获取值。我在这里看到的这种验证的最佳位置。

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

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

答案 1 :(得分:1)

我希望您现在找到了解决方案,但是对于那些对解决此问题的好方法感兴趣的人,我将解释我的解决方法。

很遗憾,正如您所说,您无法在属性海关验证功能中访问其他记录属性。

@PawełWszoła给您正确的方向,这是适用于Sails@1.0.2的完整解决方案:

// Get buildUsageError to construct waterline usage error
const buildUsageError = require('waterline/lib/waterline/utils/query/private/build-usage-error');

module.exports = {

  schema: true,

  attributes: {

    issuedAt: {
      type: 'ref',
      columnType: 'timestamp'
    },

    dueAt: {
      type: 'ref',
      columnType: 'timestamp'
    }

  },

  beforeCreate: (record, next) => {
    // This function is called before record creation so if callback method "next" is called with an attribute the creation will be canceled and the error will be returned 
    if(record.dueAt >= record.issuedAt){
      return next(buildUsageError('E_INVALID_NEW_RECORD', 'issuedAt date must be equal or greater than dueAt date', 'invoice'))
    }
    next();
  }

};
相关问题