2015-06-10 46 views
1

我的表單驗證有一些問題。使用註釋和@Valid進行Spring表單驗證

控制器:

@RequestMapping(value = REGISTER_URL, method = RequestMethod.POST) 
    public String registerPost(@Valid RegisterForm registerForm, 
           BindingResult result) { 
     if (result.hasErrors()) { 
      return REGISTER_VIEW; 
     } 
     System.out.println(registerForm.getPassword()); 
     return LOGIN_VIEW; 
    } 

查看:

<form:form action="register" commandName="registerForm" method="post"> 
      <table> 
       <tr> 
        <td>Username:</td> 
        <td><form:input path='username' /></td> 
        <td><form:errors path="username"/></td> 
       </tr> 
       <tr> 
        <td>Password:</td> 
        <td><form:password path='password'/></td> 
        <td><form:errors path="password"/></td> 
       </tr> 
       <tr> 
        <td>Repeat password:</td> 
        <td><form:password path='repeatedPassword'/></td> 
        <td><form:errors path="repeatedPassword"/></td> 
       </tr> 
       <tr> 
        <td colspan="2">&nbsp;</td> 
       </tr> 
       <tr> 
        <td colspan='2'><input name="submit" type="submit">&nbsp;<input name="reset" type="reset"></td> 
       </tr> 
      </table> 
     </form:form> 

形式:

public class RegisterForm { 

    @Size(min = 3, max = 15) 
    private String username; 

    @Size(min = 5) 
    private String password; 

    @Size(min = 5) 
    private String repeatedPassword; 

    // getters and setters omitted 
} 

當我輸入空值(用戶名,密碼和repeatedPassword),那麼不發生錯誤(我有使用調試器進行檢查)。所以它看起來沒有執行驗證。從視圖綁定值是可以的(使用調試器進行檢查)任何想法可能是錯誤的?

+0

也添加@NotEmpty註釋。 – StanislavL

+0

@StanislavL我做到了,沒有任何東西。無論如何 - 當我輸入一些隨機字符(最多4個)時,沒有任何反應。 – Stuart

+0

從您的表單中刪除動作屬性 –

回答

1

添加以下內容到你的背景:

<mvc:annotation-driven /> 
<context:component-scan base-package="xxx.xxx.xxx" /> 

在指導,他們使用"@SpringBootApplication" http://spring.io/guides/gs/validating-form-input/

@SpringBootApplication註釋等同採用@Configuration@EnableAutoConfiguration@ComponentScan與他們的默認屬性: http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html

+0

謝謝,幫助:) – Stuart