Sequelizejs - custom message for allowNull

If I have a User model:

var User = sequelize.define('User', {
  name: {
    type: Sequelize.STRING,
    allowNull: false,
    validate: {
      notEmpty: {
        msg: 'not empty'
      }
    }
  },
  nickname: {
    type: Sequelize.STRING
  }
});

      

How can I specify a message when the name is null or unspecified?

This code:

User.create({}).complete(function (err, user) {
  console.log(err);
  console.log(user);
});

      

Outputs:

{ [SequelizeValidationError: Validation error]
  name: 'SequelizeValidationError',
  message: 'Validation error',
  errors: 
   [ { message: 'name cannot be null',
       type: 'notNull Violation',
       path: 'name',
       value: null } ] }

      

Cannot be named "name cannot be null" and is not visible under my control.

Using User.create ({name: ''}) shows me my custom message 'not empty':

{ [SequelizeValidationError: Validation error]
  name: 'SequelizeValidationError',
  message: 'Validation error',
  errors: 
   [ { message: 'not empty',
       type: 'Validation error',
       path: 'name',
       value: 'not empty',
       __raw: 'not empty' } ] }

      

Is there a way to provide a message for allowNull?

thank

+3


source to share


1 answer


Unfortunately, custom messages for Null validation errors are not currently implemented. According to the original code, validation has been notNull

deprecated in favor of schema based validation, and the code within the schema validation does not allow a custom message. There is a feature request for this https://github.com/sequelize/sequelize/issues/1500 . As a workaround, you can catch Sequelize.ValidationError

and insert some special code that turns on your message.

eg.



User.create({}).then(function () { /* ... */ }).catch(Sequelize.ValidationError, function (e) {
    var i;
    for (i = 0; i < e.errors.length; i++) {
      if (e.errors[i].type === 'notNull Violation') {
        // Depending on your structure replace with a reference
        // to the msg within your Model definition
        e.errors[i].message = 'not empty';
      }
    }
})

      

+4


source







All Articles