首先:据我所知,这不是重复。问题“Grails: Custom validator based on a previous value of the field”得到an answer suggesting方法getPersistentValue()
。
我正在使用Grails 2.2.3。上下文是“当前密码”字段,用户在允许将其更改为新密码之前输入其当前密码。
所以我尝试使用 getPersistentValue()
,通过这样的方式作为custom validator:
previousPassword(validator: { val, obj ->
def previous = obj.getPersistentValue('password')
if(val != previous) {
return ['yoErrorCode']
}
})
当我现在尝试在控制器操作中更新用户的密码时:
def changePassword() {
User user = User.get(springSecurityService?.currentUser?.id)
user.validate(["previousPassword"])
user.password = springSecurityService.encodePassword(params.updatedPassword)
if (user.errors.allErrors.size() == 0) {
try {
user.save(failOnError: true)
}
catch(Exception e) {
flash.message = "An error occurred"
render(view: "password_change", model: [user: user])
return
}
flash.message = "Updated password"
render(view: "password_change", model: [user: user])
return
} else {
render(view: "password_change", model: [user: user])
return
}
}
我收到错误:
java.lang.IllegalArgumentException: object is not an instance of declaring class
我做错了吗(正确答案可能是“是”)?还是有其他方法可以做到这一点吗?