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
}
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.');
}
}
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With