2017-01-31 53 views
1

我是Spring的新手,正在嘗試使用國際化驗證消息進行驗證表單。 我爲我的登錄表單驗證使用JSR @Valid註釋。春季表格級別驗證

我想執行以下3個驗證:

  1. 檢查如果用戶名爲空
  2. 檢查密碼爲空。
  3. 檢查密碼是否對用戶名有效。

我能夠執行所有這些驗證,但問題是,在我的UI,我與第一和第二驗證相處第三驗證。

我想僅在第一次和第二次驗證通過時才顯示第三次驗證。

下面是我的JSP代碼:

   <label for="username"> <spring:message code="label.email" />      </label> 
       <form:input path="username" id="username" /> 
       <form:errors path="username" style="color: red" /> 
       <br /> 
       <br /> 
       <label for="password"> <spring:message 
         code="label.password" /></label> 
       <form:input path="password" id="password" /> 
       <form:errors path="password" style="color: red" /> 
       <br /> 
       <form:errors path="authenticated" style="color: red" /> 

我的控制器代碼:

@RequestMapping(value = "/login", method = {RequestMethod.POST, RequestMethod.GET}) 
public String authenticate(@ModelAttribute("user") @Valid User user,BindingResult result, ModelMap model, Locale locale, SessionStatus status, RedirectAttributes redirectAttrs, HttpServletRequest req){  

    if(result.hasErrors()){ 
     return "home"; 
    } 

//code to validate password against username 
} 

我Bean代碼

public class User implements Serializable { 

private static final long serialVersionUID = -7788619177798333712L; 

@NotEmpty(message = "Please enter your username.") 
private String username; 

@NotEmpty(message = "Please enter your password.") 
private String password; 

@AssertTrue(message= "Invalid username or password") 
boolean authenticated; 

這將是,如果有人能指導我很大的幫助在這個問題上。

回答

0

您可以使用class leven約束而不是單獨的字段進行驗證。

Cross field validation with Hibernate Validator (JSR 303)How can I validate two or more fields in combination?

只是介紹自己的註釋,以檢查那些實現約束或ConstraintValidator接口驗證類字段組合。

然後將註釋添加到表單類。

+0

謝謝StanislavL,謝謝你的回覆。我檢查了鏈接。我的問題是,我需要一次在UI中顯示Validation 1或2(不是3)或Validation 3(不是1和2)。 – AkashSharma