我们假设我在SailsJS中有一个Invoice
模型。它有2个日期属性:issuedAt
和dueAt
。如何创建自定义验证规则以检查截止日期是否等于或大于发布日期?
我尝试创建自定义规则,但似乎无法访问规则中的其他属性。
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
}
}
};
答案 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();
}
};