Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I validate a model by a relationship to another property?

I have a sequelize model for a tour, which has a beginning and an ending:

this.model = db.define('Tour', {
    id: {
        type: Sequelize.BIGINT(20),
        allowNull: false,
        autoIncrement: true,
        primaryKey: true
    },
    from_time: {
        type: Sequelize.DATE,
        allowNull: true
    },
    to_time:  {
        type: Sequelize.DATE,
        allowNull: true
    }
}

How can I make sure that to_time is after from_time?

(I guess validate can be used, but I don't know how)

like image 957
Martin Thoma Avatar asked Mar 09 '15 16:03

Martin Thoma


1 Answers

this in validatar will reference to the current model. So it can be written like:

// ...
to_time: {
    type: Sequelize.DATE,
    allowNull: true,
    validate: {
        isAfterFrom: function(toTime) {
            if (this.fromTime > toTime) {
                throw new Error('To time must be less then from time')
            }
        }
    }
},
// ...
like image 81
alexpods Avatar answered Sep 19 '22 23:09

alexpods