我可以使用依赖于值的自定义Sequelize验证器吗?

问题描述 投票:4回答:1

在我的模型中,我有

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

我正在尝试添加验证器,如果levelstate,那么assignedStates不应该为空。我该怎么做呢?

node.js validation sequelize.js
1个回答
4
投票

你可以使用Model validations来做到这一点。第三个参数允许您验证整个模型:

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"'
          );
        }
      }
    }
  }
);
© www.soinside.com 2019 - 2024. All rights reserved.