Java String Date Validation Using Hibernate API

后端 未结 2 1914
后悔当初
后悔当初 2021-01-03 07:14

I am attempting to validate String Date using javax.validation & Hibernate validation. i need to check given String date should be past an

相关标签:
2条回答
  • 2021-01-03 07:52

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

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

    Or else you can write your own Custom Validator.

    0 讨论(0)
  • 2021-01-03 08:09

    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}")
    

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

    Options 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)

    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;
    
    0 讨论(0)
提交回复
热议问题