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

时间:2017-12-14 17:56:20

标签: node.js validation sequelize.js

在我的模型中,我有

level

如果stateassignedStates,我尝试添加验证程序,那么{{1}}不应为空。我该怎么做呢?

1 个答案:

答案 0 :(得分: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"'
          );
        }
      }
    }
  }
);