开发者

Spring MVC: @RequestParam validation

开发者 https://www.devze.com 2023-02-22 09:08 出处:网络
In my register form i\'m using Bean Validator (JSR-303) for validate User object, and need to validate separately password confirmation, because it is not a member of User. I have a problem to assign

In my register form i'm using Bean Validator (JSR-303) for validate User object, and need to validate separately password confirmation, because it is not a member of User. I have a problem to assign error message for confirm field. How to do that ?

View:

<form:form modelAttribute="user" method="post" action="register.html">
  开发者_如何学JAVA      <div class="fcell">
            <div class="clabel"><spring:message code="label.password"/></div>
            <div class="cdata"><form:password path="password"/></div>
            <div class="cmsgs"><form:errors path="password" /></div>
        </div>
        <div class="fcell">
            <div class="clabel"><spring:message code="label.confirm"/></div>
            <div class="cdata"><input type="password" name="confirm"/></div>
            <div class="cmsgs"></div>
        </div>
</form:form>

Controller:

@RequestMapping("/register.html")
public String register(@RequestParam("confirm") String confirm, @ModelAttribute("user") @Valid User user, BindingResult result) {
    if(!DigestUtils.sha256Hex(confirm).equals(user.getPassword())) {
           /* Invalid property 'confirm' ... */                   
           result.rejectValue("confirm", "text.passwords_not_equal");
    }
    return "register";
}


In this case confirmation can be considered a part of model object, like this:

public class RegistrationForm {
    @Valid
    private User user;
    private String confirm;
    ...
}

...

public String register(@ModelAttribute("user") @Valid RegistrationForm user,
   BindingResult result) { ... }   

... 

<div class="cdata">
    <form:password path="confirm"/></div>
    <div class="cmsgs"><form:errors path="confirm" />
</div>  
... 
0

精彩评论

暂无评论...
验证码 换一张
取 消