2011-06-21 34 views
2

我對錶單輸入使用自定義驗證器。我用的是org.springframework.validation.ValidationUtils單拒絕必填字段項,如果他們是空的:在jsp中顯示在org.springframework.deflection.Errors對象上設置的錯誤

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", null, "Username is mandatory"); 

打印這些錯誤信息的工作在我的jsp:

<form:errors path="username"/> 

不過,我希望做一些更「複雜」驗證,如RegEx'ing電子郵件輸入或匹配兩次輸入的密碼:

errors.reject("verifypw", "Passwords don't match"); 

當兩個輸入的密碼不匹配,我想一個錯誤增加到OBJE的錯誤克拉。 這按預期工作,我可以用

public String submitRegisgrationForm(@ModelAttribute("user") PlatformUser user, BindingResult result) { 
    userService.validateUserInput(user, result); 
    if (!result.hasErrors()) { 
     userService.createNewUser(user); 
     return "user/success"; 
    } else { 
     return "user/register"; 
    } 
} 

唉控制器錯誤的檢查,通過errors.reject()提出的錯誤不能想通過rejectIfEmptyOrWhitespace()提出的那些訪問。

<form:errors path="verifypw"/> 
<label for="verifypw">Verify password: </label> 
<form:password path="verifypw" id="verifypw"/> 

這不會打印出jsp的任何錯誤消息。

回答

2

當您使用;

errors.reject("verifypw", "Passwords don't match"); 

您在抵制整個形式的verifypw和消息Passwords don't match錯誤代碼;你不拒絕個人領域。因此,錯誤不會出現在您的JSP中;

<form:errors path="verifypw"/> 

但是,如果你有,

<form:errors/> 

你會看到它。拒絕個人領域,使用;

errors.rejectValue("verifypw", "Passwords don't match"); 
+0

好的。應該是errors.rejectValue(「verifypw」,null,「密碼不匹配」);如果我不想使用值爲'密碼不匹配'的錯誤代碼..謝謝。 – chzbrgla