Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sequelize - how to set validate rule for Date field

I have a DATE field called completedAt, which should only accept the value on or after the current datetime.

I think I have to add a validate rule on completedAt, but I don't know how to add the condition

const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;

module.exports = function (app) {
  const sequelizeClient = app.get('sequelizeClient');
  const homework = sequelizeClient.define('homework', {
    ...,
    completedAt: {
      type: DataTypes.DATE,
      validate: {//What should I do here}
    },
  }, 
  });

  homework.associate = function (models) {
  };

  return homework;
};

like image 417
CCCC Avatar asked Dec 17 '25 14:12

CCCC


1 Answers

Create custom validator of seqlize.

completedAt: {
    type: DataTypes.DATE,
    validate: {
      customValidator(value) {
        if (new Date(value) < new Date()) {
          throw new Error("invalid date");
        }
      },
    },
  },
like image 76
MohammadTausif Shaikh Avatar answered Dec 19 '25 05:12

MohammadTausif Shaikh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!