Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate a model attribute against another model attribute in Sails?

Tags:

sails.js

Let's say I have an Invoice model in SailsJS. It has 2 date attributes: issuedAt and dueAt. How can I create a custom validation rule that check that the due date is equal or greater than the issued date?

I tried creating a custom rule, but it seems I cannot access other properties inside a rule.

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
    }

  }

};
like image 278
ragulka Avatar asked Oct 17 '13 07:10

ragulka


1 Answers

I hope you found a solution now, but for those interested to a good way to handle this i will explain my way to do it.

Unfortunatly as you said you can't access others record attributes in attribute customs validation function.

@Paweł Wszoła give you the right direction and here is a complete solution working for [email protected] :

// 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();
  }

};
like image 60
BalouFromTheJungle Avatar answered Oct 25 '22 16:10

BalouFromTheJungle