Skip to content

Built-in validator fails when value=sequelize.literal|fn #9648

@pi-kei

Description

@pi-kei

What are you doing?

const ExampleModel = sequelize.define('ExampleModel', {
    id: {
      allowNull: false,
      autoIncrement: true,
      primaryKey: true,
      type: DataTypes.INTEGER
    },
    sortingIndex: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: sequelize.literal('currval(\'"ExampleModel_id_seq"\')'),
      validate: { isInt: true }
    }
  }, {
    timestamps: true,
    paranoid: true,
    tableName: 'ExampleModel'
});
// Case #1
ExampleModel.create({ sortingIndex: 5 });
// Case #2
ExampleModel.create({});
// Case #3
ExampleModel.create({ sortingIndex: 'abc' });

What do you expect to happen?

In Case #1 I expect successful creation of an instance with sortingIndex = 5.
In Case #2 I expect successful creation of an instance with sortingIndex = default value (same value as id attribute).
In Case #3 I expect validation error.

What is actually happening?

In Case #2 I got validation error Validation isInt on sortingIndex failed with value { val: 'currval(\'"ExampleModel_id_seq"\')' }.
In Case #1 and Case #3 everything worked as expected.

My temporary workaround

Create custom validator which checks if current value is not SequelizeMethod and then runs built-in validator.

sortingIndex: {
  type: DataTypes.INTEGER,
  allowNull: false,
  defaultValue: sequelize.literal('currval(\'"ExampleModel_id_seq"\')'),
  validate: {
    isIntOrMethod(sortingIndex) {
      if (
        !(sortingIndex instanceof sequelize.Utils.SequelizeMethod) &&
        !sequelize.Validator.isInt(String(sortingIndex))
      ) {
        throw new Error('sortingIndex must be integer');
      }
    }
  }
}

Dialect: postgres
Dialect version: 7.4.3
Database version: 9.6
Sequelize version: 4.38.0
Tested with latest release: No (If yes, specify that version)

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: bugDEPRECATED: replace with the "bug" issue type

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions