续集自定义验证器

sequelize custom validator

我想参考现有字段创建自定义字段验证器。我所做的是创建一个自定义验证器:

const User = sequelize.define('User', {
    postalCode: {
      type: DataTypes.STRING
    },
    country: DataTypes.STRING,
  }, {
    validate: {
      wrongPostalCode() {
        if (this.postalCode && this.country) {
          if (!validator.isPostalCode(String(this.postalCode), this.country)) {
            throw new Error('Wrong postal code')
          }
        }
      }
    }
  });
  User.associate = (models) => {
    // TO DO
  };
  return User;
};

正如您在下面的错误消息中看到的,我们正在获取此验证器,但在 "path" 行中有验证器名称。例如,我想将其更改为 "postalCode" 或以某种方式将其与模型中的一个字段连接起来。这对我来说非常重要,因为这与前端有关并解析它以正确控制表单。

enter image description here

有什么办法吗?

先谢谢你:)

您是否尝试过使用 custom validator for the field?我没有尝试过以下代码,但应该可以工作,并且 link 验证器到 postalCode 字段。

const User = sequelize.define('User', {
  postalCode: {
    type: DataTypes.STRING,
    validate: {
      wrongPostalCode(value) {
        if (this.country) {
          if (!validator.isPostalCode(String(this.postalCode), this.country)) {
            throw new Error('Wrong postal code');
          }
        }
      }
    }
  },
  country: DataTypes.STRING,
});