Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequelizejs - custom message for allowNull

If I have a model User:

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 for when name is null or not provided?

This code:

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

Produces:

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

The message 'name cannot be null' is generated and doesn't appear to be 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 supply the message for allowNull ?

Thanks

like image 705
prule Avatar asked Sep 28 '14 01:09

prule


1 Answers

Unfortunately custom messages for Null validation errors are not currently implemented. According to the source code, notNull validation is deprecated in favor of a schema-based validation and the code within the schema validation does not allow for a custom message. There is a feature request for this at https://github.com/sequelize/sequelize/issues/1500. As a workaround you can catch the Sequelize.ValidationError and insert some custom code that includes your message.

e.g.

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';
      }
    }
})
like image 53
user4040648 Avatar answered Oct 11 '22 12:10

user4040648