将参数传递给Grails自定义验证器

时间:2011-09-12 13:59:12

标签: grails grails-validation

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']
        })
    }

}

1 个答案:

答案 0 :(得分:2)

validator约束为要验证的对象采用参数:

validator: { val, obj ->
    if(!val.startsWith(obj.generatedPassword)) ...
}