使用Hibernate API进行Java字符串日期验证 [英] Java String Date Validation Using Hibernate API
问题描述
我正在尝试使用javax.validation
&休眠验证.我需要检查给定的字符串日期应该是过去的,并且它应该是正确的yyyyMMdd
格式,并具有所有限制,例如leap年,30th
,31st
天.
I am attempting to validate String Date using javax.validation
& Hibernate validation. i need to check given String date should be past and it should be correct yyyyMMdd
format with all constraints like leap year, 30th
, 31st
day.
public class UserInformation {
@NotNull
public String idNum = null;
@NotNull
//@Past
@Pattern(regexp="\\d{4}(1[012]|0[1-9])(3[01]|[12]\\d|0[0-9])")
public String dob= null;
}
我尝试使用此代码,但无法正常工作.有什么解决办法.如果我们有自定义验证器,那么它是否在字段级别.请提供建议或代码段.
I tried with this code but not working. Is there any solution. if we have custom validator then is it in field level.Please give suggestion or code snippet.
推荐答案
选项1
将模式更改为此:
Option 1
Change your pattern to this:
Pattern(regexp = "([0-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/[0-9]{4}")
但是请记住,这种验证不会检查2月是否少于28/29天以及其他日期限制.
But keep in mind that this kind of validation is not checking if February has less than 28/29 days, and other dates constraints.
创建自定义约束验证器
注释
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = CheckDateValidator.class)
@Documented
public @interface CheckDateFormat {
String message() default "{message.key}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
String pattern();
}
Validator类
Validator class
有了Date对象,您可以进行任何其他想要的验证(例如过去的拒绝日期)
Having the Date object you can do any other validation you want (like refuse dates in the past)
public class CheckDateValidator implements ConstraintValidator<CheckDateFormat, String> {
private String pattern;
@Override
public void initialize(CheckDateFormat constraintAnnotation) {
this.pattern = constraintAnnotation.pattern();
}
@Override
public boolean isValid(String object, ConstraintValidatorContext constraintContext) {
if ( object == null ) {
return true;
}
try {
Date date = new SimpleDateFormat(pattern).parse(object);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
使用
@CheckDateFormat(pattern = "ddMMyyyy")
private String value;
这篇关于使用Hibernate API进行Java字符串日期验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!