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
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';
}
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With