开发者

How to internationalize spring-mvc form error messages?

开发者 https://www.devze.com 2023-02-07 06:54 出处:网络
I want to translate the default error messages for form validation, for example, when I annotate a field as @NotEmpty, I should receive an error like:

I want to translate the default error messages for form validation, for example, when I annotate a field as @NotEmpty, I should receive an error like:

may not be empty

when I left the field empty. Now I want this mes开发者_如何学运维sage in other languages, so what should I do in order to translate them? I want this to work with every field annotated with @NotEmpty, and also for other messages...

Thanks!


Spring can hook up into your internationalized error codes I think ...

My validator class extends Validator and implements setting a MessageSource and then can pass in errorCode like below and Im guessing it autolooks it up via the MessageSource set (which i set via a Spring Bean):

public static void rejectIfEmptyOrWhitespace(Errors errors,
                                             String field,
                                             String errorCode,
                                             String defaultMessage)

http://docs.spring.io/spring-framework/docs/4.2.x/javadoc-api/org/springframework/validation/ValidationUtils.html#rejectIfEmptyOrWhitespace-org.springframework.validation.Errors-java.lang.String-java.lang.String-java.lang.String-

Here is a pretty close example to what I have (minus they use LocaleResolver): http://vardhan-java2java.blogspot.com/2010/08/spring-internationalization-i18n.html


You can add custom messages to @NotEmpty by using it like this:

@NotEmpty( message = "Your error message")
0

精彩评论

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

关注公众号