Spring MVC Bean Validation --Data Type Validation

Multi tool use
Spring MVC Bean Validation --Data Type Validation
public class User {
@NotNull(message="Age is Required")
@Min(value = 18, message = "Age must be greater than or equal to 18")
@Max(value = 150, message = "Age must be less than or equal to 150")
private Integer age;
}
If the User enters "String Value" in age, I want to validate them and should provide error message "Age is Invalid".
@OnlyNumber(message = "Age is Invalid") //Like This
Which Annotation helps in validating this kind of Type Validation,
Similarly if the use enters different type format instead of Date. How
do we handle them and provide custom error message.
@OnlyNumber
1 Answer
1
There is no Hibernate validation for that because exception is thrown when Spring tries to bind String value with Integer field.
What you can do if you want to display customized message for that exception is configure Spring to use message.properties file and specify 'typeMismatch.user.age' message or global message for typeMismatch.
For example (Spring 3.2 and Hibernate Validator 4.3), in servlet-config.xml
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
p:basename="classpath:messages/messages">
</bean>
In src/main/resources/messages/messages.properties
typeMismatch = Invalid data format!
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
you can create your own
@OnlyNumber
– Pravin
Mar 24 '15 at 15:25