我正在使用 Sequelize 4.38.0
并在用户模型上对电子邮件进行自定义验证。
自定义验证的构建方式(见下文),如果电子邮件属性没有更改,我需要跳过验证。否则它会停止整个更新操作(因为它认为电子邮件地址已被占用)。
如何仅在值发生变化时才对属性运行验证?
email: {
type: DataTypes.STRING,
allowNull: false,
validate: {
isEmail: {
msg: 'Wrong email format',
},
notEmpty: {
msg: 'Email has to be present',
},
isUnique: function(value, next) {
User.find({
where: {
email: value,
organizationId: this.organizationId,
},
})
.then(function(result) {
if (result === null) {
return next()
} else {
return next(' Email address already in use')
}
})
.catch(err => {
return next()
})
},
},
},
最佳答案
用这样的条件解决了它:
isUnique: function(value, next) {
if (this.changed('email')) {
User.find({
where: {
email: value,
organizationId: this.organizationId,
},
})
.then(function(result) {
if (result === null) {
return next()
} else {
return next(' Email address already in use')
}
})
.catch(err => {
return next()
})
} else {
next()
}
},
关于node.js - 仅当值发生变化时才验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53283446/