我正在实施一个注册页面,其中包括:用户名,密码,确认密码,其他信息和reCAPTCHA。
如何确认密码?这是我的尝试,但当我尝试注册密码不匹配时,我仍然可以注册...
User.groovy:
String password
transient confirmPassword
static constraints = {
//removed other constraints
password blank: false, nullable: false, validator: {password, obj ->
def confirmPassword = obj.properties['confirmPassword']
if(confirmPassword == null) return true
confirmPassword == password ? true : ['mismatch.passwords'] //"Passwords do not match"
}
//confirmPassword blank: false, nullable: false, bindable: true
}
UserController.groovy:
def save() {
def userInstance = new User(params)
def recaptchaOK = true
if (!recaptchaService.verifyAnswer(session, request.getRemoteAddr(), params)) {
recaptchaOK = false
}
if(!userInstance.hasErrors() && recaptchaOK && userInstance.save()) {
recaptchaService.cleanUp(session)
if (!userInstance.save(flush: true)) {
render(view: "create", model: [userInstance: userInstance])
return
}
flash.message = message(code: 'create.user.successful')
redirect(controller: 'login', action: "auth", id: userInstance.id)
sendSignUp(userInstance.email,userInstance.firstName, userInstance.lastName)
UserRole.create(userInstance, Role.findByAuthority("ROLE_USER"),true)
}
else {
flash.recaptchafailed = message(code: 'recaptcha.failed')
render(view: "create", model: [userInstance: userInstance])
}
}
create.gsp(只是密码和确认密码的字段):
<div class="row">
<div class="col-md-12 form-item fieldcontain ${hasErrors(bean: userInstance, field: 'password', 'error')}">
<div class="col-md-3">
<label for="password">
<g:message code="user.password.label" default="Password" />
<span class="required-indicator">*</span>
</label>
</div>
<div class="col-md-9">
<g:textField name="password" required="" class="form-control input-sm form-ship" value="${userInstance?.password}"/>
</div>
</div>
*
答案 0 :(得分:2)
String password;
String confirmPassword;
static constraints = {
password nullable: false, blank: false
confirmPassword nullable: false, blank: false, validator: { val, object ->
if ((val != object.password)) {
return 'passwordMismatch'
}
return true
尝试此密码不匹配
答案 1 :(得分:0)
我最近遇到了同样的问题。问题是您的字段confirmPassword是暂时的。我不知道它是否仍然是真的,但验证器并不适用于瞬态值。
就我而言,我在服务中使用验证解决了问题:
def passwordValidation(String password, String passwordConfirmation) {
String pattern = "((?=.*[0-9])(?=.*[a-zA-Z]).{8,})";
if (password.equals(passwordConfirmation) && password.matches(pattern)) {
return true
} else {
return false
}
}
我希望它会有所帮助。