使用 Hibernate API 的 Java 字符串日期验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41718208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:05:41  来源:igfitidea点击:

Java String Date Validation Using Hibernate API

javabean-validation

提问by deadend

I am attempting to validate String Dateusing javax.validation& Hibernate validation. i need to check given String date should be past and it should be correct yyyyMMddformat with all constraints like leap year, 30th, 31stday.

我正在尝试 使用& Hibernate 验证来验证字符串日期javax.validation。我需要检查给定的字符串日期应该是过去的,并且它应该是正确的yyyyMMdd格式,并且具有所有约束,例如闰年30th31st日。

 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.

我尝试使用此代码但不起作用。有什么解决办法。如果我们有自定义验证器,那么它是否在字段级别。请给出建议或代码片段。

回答by Rafael Teles

Option 1

选项1

Change your pattern to this:

将您的模式更改为:

Pattern(regexp = "([0-2][0-9]|3[0-1])\/(0[1-9]|1[0-2])\/[0-9]{4}")

But keep in mind that this kind of validation is not checking if February has less than 28/29 days, and other dates constraints.

但请记住,这种验证不会检查二月是否少于 28/29 天,以及其他日期限制。

Options 2

选项 2

Create your custom constraint validator

创建您的自定义约束验证器

Annotation

注解

@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 class

验证器类

Having the Date object you can do any other validation you want (like refuse dates in the past)

拥有 Date 对象,您可以进行任何其他您想要的验证(例如拒绝过去的日期)

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;
        }
    }
}

Use

利用

@CheckDateFormat(pattern = "ddMMyyyy")
private String value;

回答by shazin

If you use Spring-Context Module as dependency you can use @DateTimeFormatand do the following.

如果您使用 Spring-Context Module 作为依赖项,您可以使用@DateTimeFormat并执行以下操作。

    @NotNull
    @DateTimeFormat(pattern="yyyyMMdd")
    public String dob= null;

Or else you can write your own Custom Validator.

或者,您可以编写自己的自定义验证器。