node.jsvalidationsequelize.js

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;
};


Solution

  • Create custom validator of seqlize.

    completedAt: {
        type: DataTypes.DATE,
        validate: {
          customValidator(value) {
            if (new Date(value) < new Date()) {
              throw new Error("invalid date");
            }
          },
        },
      },