如果我有模型用户:
var User = sequelize.define('User', {
name: {
type: Sequelize.STRING,
allowNull: false,
validate: {
notEmpty: {
msg: 'not empty'
}
}
},
nickname: {
type: Sequelize.STRING
}
});
如果名称为null或未提供,如何指定消息?
这段代码:
User.create({}).complete(function (err, user) {
console.log(err);
console.log(user);
});
产生:
{ [SequelizeValidationError: Validation error]
name: 'SequelizeValidationError',
message: 'Validation error',
errors:
[ { message: 'name cannot be null',
type: 'notNull Violation',
path: 'name',
value: null } ] }
消息“名称不能为空”已生成,似乎不受我的控制。
使用User.create({name:''})向我显示我的自定义消息“不为空”:
{ [SequelizeValidationError: Validation error]
name: 'SequelizeValidationError',
message: 'Validation error',
errors:
[ { message: 'not empty',
type: 'Validation error',
path: 'name',
value: 'not empty',
__raw: 'not empty' } ] }
有没有办法为allowNull提供消息?
谢谢
不幸的是,当前未实现针对Null验证错误的自定义消息。根据源代码,notNull
不赞成使用验证,而建议使用基于架构的验证,并且架构验证中的代码不允许自定义消息。在https://github.com/sequelize/sequelize/issues/1500上有对此功能的要求。作为一种解决方法,您可以捕获Sequelize.ValidationError
并插入一些包含您的消息的自定义代码。
例如
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';
}
}
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句