validationsequelize.jscustom-validatorssequelize-cli

sequelize custom validator


I would like to create custom field validator with reference to existing field. What I did is to create a 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;
};

As you can see below in error message, we are getting this validator but in the row "path" there is validator name. I would like to change it for example to "postalCode" or somehow connect it with one field from the model. It is very important for me as this is related to Front-End and to parse it to correct form control.

enter image description here

Is there any way to do it?

Thank you in advanced :)


Solution

  • Have you tried to use a custom validator for the field instead? I haven't tried the following piece of code but should work and link the validator to the postalCode field.

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