Reputation: 1073
I can't get my messages in messages.properties to be used during Spring validation of my form backing objects.
app-config.xml:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
WEB-INF/classes/messages.properties:
NotEmpty=This field should not be empty.
Form Backing Object:
...
@NotEmpty
@Size(min=6, max=25)
private String password;
...
When I loop through all errors in the BindingResult and output the ObjectError's toString I get this:
Field error in object 'settingsForm' on field 'password': rejected value []; codes [NotEmpty.settingsForm.password,NotEmpty.password,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [settingsForm.password,password]; arguments []; default message [password]]; default message [may not be empty]
As you can see the default message is "may not be empty" instead of my message "This field should not be empty".
I do get my correct message if I inject the messageSource into a controller and output this: messageSource.getMessage("NotEmpty", new Object [] {"password"}, "default empty message", null);
So why isn't the validation using my messages.properties? I'm running Spring 3.1.1. Thanks!
Upvotes: 3
Views: 11301
Reputation: 3004
When you want to set the custom message for any field using JSR 303 validations then you need to specify the bean name(LoginForm) and field name(password) in key of the message in property file. The format is CONSTRAINT_NAME.COMMAND_NAME.FIELD_NAME
NotEmpty.loginform.password=This field should not be empty.
Upvotes: 2
Reputation: 47954
By default HibernateValidator will get all of its messages from /WEB-INF/classes/ValidationMessages.properties
It reads this file directly itself, not through the Spring MessageSource.
If you want translations from a Spring Message source, set one on the LocalValidatorFactoryBean. This does require you to manually set up a validation bean inside your dispatcher servlet, rather than rely on mvc:annotation-driven.
Upvotes: 7
Reputation: 1023
@NotEmpty has a message property you can set on it. Since you're not setting it, it uses the default message.
@NotEmpty(message="{NotEmpty}")
should give you what you are looking for.
Upvotes: 1