Reputation: 592
I have an object.
public class MyObject
{
....
@Column(name = "a_number") @NotNull @NumberFormat(style = Style.NUMBER) @Min(1)
private Integer aNumber;
...
//getters and setters
}
In my controller I have @Valid annotation on my object being posted. I do have validation working on all my other fields in the class (their all Strings) except this number. If I enter a number from my form it works fine and if I violate the @Min(1) it also gives me the correct validation error. My problem however is that if you enter a string instead of a number it throw a NumberFormatException.
I've seen many examples of Integer and validation but no one accounts for if you enter a string into the form being posted. Do I need to do the validation else where? Javascript? I would like a solution that falls in line with the rest of spring validation so I could use this in other classes. I would just like an error stating it must be numeric. Also I tried using the @Pattern annotation but apparently thats just for strings.
Suggestions?
Upvotes: 8
Views: 19174
Reputation: 401
Still relevant, so I'll add the programmatical approach of message source bean definition:
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
Upvotes: 0
Reputation: 1260
For those who did not get the idea right here is what to do in spring 4.2.0
.
Create a file name messages.properties
in WEB-INF > classes
folder. And put the above type mismatch messages in that file.
In spring configuration or servlet.xml
file create the following bean.
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="messages"></beans:property>
</beans:bean>
And for your model attribute like private Integer aNumber;
in the question along with other validation rules this rule is also applied for type mismatch conversion. You will get your desired message in this.
<form:errors path="aNumber"></form:errors>
Hope it helps others.
Upvotes: 4
Reputation: 9488
You can add the following to your file which controls your error messages (these are the generic ones it looks for in the case of a type mismatch:
typeMismatch.commandObjectName.aNumber=You have entered an invalid number for ...
typeMismatch.aNumber=You have entered an invalid number for ...
typeMismatch.java.lang.Integer=You have input a non-numeric value into a field expecting a number...
typeMismatch=You have entered incorrect data on this page. Please fix (Catches all not found)
Upvotes: 9