http://www.grails.org/doc/latest/ref/Constraints/validator.html
我有一个项目,我希望用户使用我通过短信提供的临时密码登录。因此,在登录时,我想使用自定义验证器来检查我使用Java类创建的密码。
class LoginCommand {
String telephoneNumber; /* the users telephone number, used for logging in */
String password; /* the password they entered, must match the generated pw below */
/* the generated password, which has been sent to the user via SMS */
String generatedPassword = PasswordGenerator.passwordGenerator(telephoneNumber)
def jsecSecurityManager
boolean authenticate() {
def authToken = new UsernamePasswordToken(telephoneNumber, password)
try {
this.jsecSecurityManager.login(authToken)
return true
} catch (AuthenticationException ae) {
return false
}
}
static constraints = {
telephoneNumber blank:false
password blank:false
/* the problem lies here, I need to pass that generatedPassword as an argument to the validator here, however I have no idea how to do that */
password(validator: {
if (!it.startsWith(generatedPassword)) return ['invalid.password']
})
}
}
validator
约束为要验证的对象取一个参数:
validator: { val, obj ->
if(!val.startsWith(obj.generatedPassword)) ...
}