Spring MVC Bean 验证 -- 数据类型验证

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;

}

如果用户输入 "String Value" 年龄,我想验证它们并提供错误消息 "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.

没有 Hibernate 验证,因为当 Spring 尝试将字符串值与整数字段绑定时会抛出异常。

如果您想为该异常显示自定义消息,您可以做的是配置 Spring 以使用 message.properties 文件并为类型不匹配指定 'typeMismatch.user.age' 消息或全局消息。

例如(Spring 3.2 和 Hibernate Validator 4.3),在 servlet-config.xml

<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
p:basename="classpath:messages/messages">
</bean>

在src/main/resources/messages/messages.properties

typeMismatch = Invalid data format!