Has*_*haf 5 javascript node.js sequelize.js
我正在尝试为字段username和的唯一约束违规设置验证消息email。但是,每当输入已使用的用户名时,它都会显示为该email属性定义的消息,但会显示该属性的输入username,并表示此输入适用于该username属性。我该如何解决这个问题?这是我的代码:
module.exports = function (sequelize, DataTypes) {
var users = sequelize.define('users', {
full_name: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: {
args: [5, 50],
msg: 'Your full name may be 5 to 50 characters only.'
}
}
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: {
msg: 'This email is already taken.'
},
validate: {
isEmail: {
msg: 'Email address must be valid.'
}
}
},
username: {
type: DataTypes.STRING,
allowNull: false,
unique: {
msg: 'This username is already taken.'
},
validate: {
len: {
args: [5, 50],
msg: 'Your username may be 5 to 50 characters only.'
}
}
},
password: {
type: DataTypes.STRING,
allowNull: false,
validate: {
len: {
args: [5, 72],
msg: 'Your password may be 5 to 72 characters only.'
}
}
},
rank: {
type: DataTypes.INTEGER,
allowNull: false,
validate: {
isInt: true
}
}
}, {
hooks: {
beforeValidate: function (user, options) {
if (typeof user.email === 'string') {
user.email = user.email.toLowerCase();
}
if (typeof user.username === 'string') {
user.username = user.username.toLowerCase();
}
}
}
});
return users;
};
Run Code Online (Sandbox Code Playgroud)
这是我从输入得到的输出:
{
"name": "SequelizeUniqueConstraintError",
"message": "Validation error",
"errors": [
{
"message": "This email is already taken.",
"type": "unique violation",
"path": "username",
"value": "hassan"
}
],
"fields": {
"username": "hassan"
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它表示用户名不是唯一的,而是使用为电子邮件属性定义的消息。
小智 5
这是可能的尝试这样
unique: {
arg: true,
msg: 'This username is already taken.'
},
Run Code Online (Sandbox Code Playgroud)
这是不可能的,因为它是一个模式验证器,而不是属于对象内部的通用验证器validate: { }。唯一的解决方法是在对象中包含defaultValue: ''并拥有一个notNull对象validate。否则,仅删除allowNull就会禁用大多数validate: {}检查。
| 归档时间: |
|
| 查看次数: |
8384 次 |
| 最近记录: |