Fiyin Akinsiku
Fiyin Akinsiku

Reputation: 188

How to customize sequelize enum error message?

How can I set this model to return a customized error message like Jamaica is not a valid input for enum instead of the standard error message? The solutions I've found like this only apply to DATATYPES.STRING but I need something that works for

This is the Model:

module.exports = (sequelize, DataTypes) => {
  const Country = sequelize.define("Countries", {
    nameOfCountry: {
      type: DataTypes.ENUM(
        "Nigeria",
        "Ethiopia",
      ),
      allowNull: false,
    }),
  });

Upvotes: 1

Views: 1921

Answers (1)

Aryan
Aryan

Reputation: 3636

You can add custom error msg and validations like shown in this docs of sequelize

you have to create custom sequelize validate function or you can pass arguments

module.exports = (sequelize, DataTypes) => {
  const Country = sequelize.define("Countries", {
    nameOfCountry: {
      type: DataTypes.ENUM(
        "Nigeria",
        "Ethiopia",
      ),
      allowNull: false,
      validate: {
        customValidator(value) {
          if (value !== "Nigeria" || value !== "Ethiopia") {
            throw new Error("error msg you want to write");
          }
        }
      }
    },
});

or If you don't want to use custom validate you can use this

  validate: {
    isIn: {
      args: [['Nigeria', 'Ethiopia']],
        msg: "Must be Nigeria or Ethiopia"
    }
  }

Upvotes: 3

Related Questions