我想验证日期格式YYYY-MM-DD_hh:mm:ss
@Past //validates for a date that is present or past. But what are the formats it accepts
如果那不可能,我想使用@Pattern
。但什么是regex
上述格式用于@Pattern
?
@Past
仅支持Date
and Calendar
但不是字符串,因此没有日期格式的概念。
您可以创建自定义约束,例如@DateFormat
它确保给定的字符串遵循给定的日期格式,并具有如下约束实现:
public class DateFormatValidatorForString
implements ConstraintValidator<DateFormat, String> {
private String format;
public void initialize(DateFormat constraintAnnotation) {
format = constraintAnnotation.value();
}
public boolean isValid(
String date,
ConstraintValidatorContext constraintValidatorContext) {
if ( date == null ) {
return true;
}
DateFormat dateFormat = new SimpleDateFormat( format );
dateFormat.setLenient( false );
try {
dateFormat.parse(date);
return true;
}
catch (ParseException e) {
return false;
}
}
}
请注意,SimpleDateFormat
实例不得存储在验证器类的实例变量中,因为它不是线程安全的。或者你可以使用快速日期格式 http://commons.apache.org/proper/commons-lang/apidocs/index.html?org/apache/commons/lang3/time/FastDateFormat.html来自 commons-lang 项目的类,可以安全地从多个线程并行访问。
如果您想添加对字符串的支持@Past
你可以通过实现一个验证器来实现ConstraintValidator<Past, String>
并使用 XML 进行注册约束映射 http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-mapping-xml-constraints。但是,无法指定预期的格式。或者,您可以实现另一个自定义约束,例如@PastWithFormat
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)