验证日期 - Bean验证注解 - 具有特定的格式 [英] Validating Date - Bean validation annotation - With a specific format
问题描述
我想验证日期格式为 YYYY-MM-DD_hh:mm:ss
@Past //验证当前或过去的日期。但是,它接受的格式是什么
如果不行的话,我想用 @Pattern
。但是在 @Pattern
中使用上面的格式是什么 regex
?
<只有
Date
和 Calendar
但不是字符串,所以没有日期格式的概念。 你可以创建一个自定义约束,例如 @DateFormat
确保一个给定的字符串遵守给定的日期格式,约束实现如下:
public class DateFormatValidatorForString
实现ConstraintValidator< DateFormat,String> {
私有字符串格式;
public void initialize(DateFormat constraintAnnotation){
format = constraintAnnotation.value();
public boolean isValid(
String date,
ConstraintValidatorContext constraintValidatorContext){
if(date == null){
返回true;
}
DateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setLenient(false);
尝试{
dateFormat.parse(date);
返回true;
catch(ParseException e){
return false;
请注意 SimpleDateFormat
实例不能存储在验证器类的实例变量中,因为它不是线程安全的。或者,您可以使用 FastDateFormat 类从commons-lang项目,可安全地从多个线程并行访问。
如果您想要支持字符串 @Past
你可以通过实现一个实现 ConstraintValidator< Past,String>
的验证器并使用XML 约束映射。但是,没有办法指定预期的格式。或者,您可以实现另一个自定义约束,如 @PastWithFormat
。
I would like to validate a Date for the format YYYY-MM-DD_hh:mm:ss
@Past //validates for a date that is present or past. But what are the formats it accepts
If thats not possible, I would like to use @Pattern
. But what is the regex
for the above format to use in @Pattern
?
解决方案 @Past
supports only Date
and Calendar
but not Strings, so there is no notion of a date format.
You could create a custom constraint such as @DateFormat
which ensures that a given string adheres to a given date format, with a constraint implementation like this:
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;
}
}
}
Note that the SimpleDateFormat
instance must not be stored in an instance variable of the validator class as it is not thread-safe. Alternatively you could use the FastDateFormat class from the commons-lang project which safely can be accessed from several threads in parallel.
If you wanted to add support for Strings to @Past
you could do so by implementing a validator implementing ConstraintValidator<Past, String>
and registering using an XML constraint mapping. There would be no way to specify the expected format, though. Alternatively you could implement another custom constraint such as @PastWithFormat
.
这篇关于验证日期 - Bean验证注解 - 具有特定的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!