Reputation: 6042
I validate in two ways - using spring validator for custom validation and javax.validation for quick and general
Spring does things neatly, where this code will go exactly to document with given locale and extract text required.
private Errors checkPasswordMatch(Person p, Errors errors) {
if (!p.getPassword().equals(p.getRepeatedPassword())) {
errors.rejectValue("password", "person.password.mismatch");
errors.rejectValue("repeatedPassword", "person.password.mismatch");
}
return errors;
}
Javax is less hassle, but there is no way to produce message in different languages.
@NotNull
@Size(min = 10, max = 10, message = "size must be 10 characters")
protected String birthDate;
How to advise javax to go to some GB.properties or US.properties or IT.properties file to extract messages same way spring does depending on user locale?
Upvotes: 0
Views: 2921
Reputation: 14558
@Size(min = 10, max = 10, message = "{birthDate.size}")
protected String birthDate;
in (create one in classpath if you dont have one) ValidationMessages.properties
define as birthDate.size = some message
EDIT 1:
Keep files seperate. ValidationMessages needs to be shipped/packaged along with your beans all the time unlike your app specific messages. You dont need to define a bean for ValidationMessages.properties file. It will be picked up automatically
Upvotes: 5
Reputation: 88747
I don't know javax.validation that well, but I assume you get the message in the ValidationException
which is thrown.
Thus, define a message key for the exception instead of a message and when displaying the exception/messages do a lookup in the corresponding resource bundle yourself.
In Struts2 we'd do something like this:
@Size(min = 10, max = 10, message = "size.exact.10")
protected String birthDate;
//in the JSP display the message:
<s:text name="%{exception.message}"/>
I guess you could do something similar.
Upvotes: 0