Can I customize custom Sequelize validators based on values?

In my model I have

  level: {
    type: DataTypes.ENUM('state', 'service-area'),
    allowNull: false,
    validate: {
      isIn: {
        args: [
          ['state', 'service-area']
        ],
        msg: 'level should be one of state,service-area'
      }
    }
  },
      assignedStates: {
        type: DataTypes.ARRAY(DataTypes.STRING),
        allowNull: true
      },
      assignedServiceAreas: {
        type: DataTypes.ARRAY(DataTypes.STRING),
        allowNull: true
      },

I am trying to add a validator if levelis state, and then assignedStatesshould not be null. How should I do it?

+4
source share
1 answer

You can do this using Model Check . There is a third parameter that allows you to check the entire model:

const Levels = {
  State: 'state',
  ServiceArea: 'service-area'
}

const Location = sequelize.define(
  "location", {
    level: {
      type: DataTypes.ENUM(...Object.values(Levels)),
      allowNull: false,
      validate: {
        isIn: {
          args: [Object.values(Levels)],
          msg: "level should be one of state,service-area"
        }
      }
    },
    assignedStates: {
      type: DataTypes.ARRAY(DataTypes.STRING),
      allowNull: true
    },
    assignedServiceAreas: {
      type: DataTypes.ARRAY(DataTypes.STRING),
      allowNull: true
    }
  }, {
    validate: {
      assignedValuesNotNul() {
        // Here "this" is a refference to the whole object.
        // So you can apply any validation logic.
        if (this.level === Levels.State && !this.assignedStates) {
          throw new Error(
            'assignedStates should not be null when level is "state"'
          );
        }

        if (this.level === Levels.ServiceArea && !this.assignedServiceAreas) {
          throw new Error(
            'assignedSerivceAreas should not be null when level is "service-areas"'
          );
        }
      }
    }
  }
);
Run code
+1
source

Source: https://habr.com/ru/post/1690801/


All Articles