Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelizejs "isAfter" validation with other field

In the Sequelize's docs, they have mention following way to restrict a date field value to after a certain date.

validate: {
    isAfter: '2018-10-02'
}

But I want to perform this validation against another date field from req.body

Like

validate: {
    isAfter: anotherFieldName    // fieldname instead of static value
}
like image 839
Amarjit Singh Avatar asked Mar 05 '23 07:03

Amarjit Singh


1 Answers

The field validators do not have access to the model instance's other properties. In order to validate that two values on an instance pass your validation check, You should make use of Sequelize's custom validate object in the model options:

const SomeModel = db.define(
  'some_model',
  {
    start_date: {
      type: Sequelize.DATEONLY,
      validate: {
        isDate: true
      }
    },
    end_date: {
      type: Sequelize.DATEONLY,
      validate: {
        isDate: true
      }
    },
  },
  {
    validate: {
      startDateAfterEndDate() {
        if (this.start_date.isAfter(this.end_date)) {
          throw new Error('Start date must be before the end date.');
        }
      }
    }
  }
);
like image 128
mcranston18 Avatar answered Mar 15 '23 02:03

mcranston18