2011-01-26 92 views

回答

40

JSR 303 default message interpolation algorithm允許您通過提供名爲ValidationMessages的資源包來自定義消息。在包含classpath中創建一個ValidationMessages.properties文件:

javax.validation.constraints.NotNull.message=CUSTOM NOT NULL MESSAGE 
javax.validation.constraints.Size.message=CUSTOM SIZE MESSAGE 

這改變了默認消息爲@Size約束,所以你應該使用@Size約束,而不是Hibernate的特定@Length約束。

除了更改所有約束的默認消息,您可以更改特定約束實例的消息。設置message屬性上的約束:

@NotNull(message = "{email.notnull}") 
private String email; 

和消息添加到ValidationMessages.properties文件:

email.notnull=E-mail address is required 
0

By Spring我假設你的意思是Spring MVC。

從下面的參考 http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html

在這裏你去 -

您創建一個驗證器類 -

public class UserValidator implements Validator { 

    public boolean supports(Class candidate) { 
     return User.class.isAssignableFrom(candidate); 
    } 

    public void validate(Object obj, Errors errors) { 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "required", "Field is required."); 
     ValidationUtils.rejectIfEmptyOrWhitespace(errors, "lastName", "required", "Field is required."); 
    } 
} 

在你在上面領域所需的任何驗證文本把。

在JSP中,你將需要以下標籤 -

<tr> 
    <td>First Name:</td> 
    <td><form:input path="firstName" /></td> 
    <!-- Show errors for firstName field --> 
    <td><form:errors path="firstName" /></td> 
</tr> 

這樣的firstName任何驗證錯誤將被打印出來。

+0

我用註釋驗證像@NotNull。那麼在哪裏存儲消息在Spring jar?我認爲我需要編輯他們 – 2011-01-26 14:27:19

+0

@ apache-fan我投下你的答案,因爲OP說關於現代JSR303風格的驗證,而不是關於舊的春天特定。 – 2011-10-05 17:41:45