Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Validation Between Two Date Fields?

In my Spring Application, i'm Using Hibernate Validator for Validation Purpose.

When i'm doing simple Validation like @NotEmpty, @Email .. i'm easily working

But When coming to Date field, giving Problem...

Problem is in my Jsp page i'm getting values type as String then i'm convert String to Date..

Hear is my Example...

@NotEmpty(message = "Write Some Description")
private String description;

private String fromDateMonth;

private String fromDateYear;

private String toDateMonth;

private String toDateYear;

i'm converting this fromDateMonth and fromDateYear into Date in this my Controller class.

So is their any Possibility to add Validator Annotation in Controller class?

Other wise what should i'm do hear? give me suggestions...

like image 421
Java Developer Avatar asked Dec 12 '22 15:12

Java Developer


2 Answers

If you want to validate that fromDate is before toDate, you can write a custom validator to perform this multi-field validation. You write a custom validator, and you also define a custom annotation which is placed on the bean being validated.

See the following answers for more information.

  • Cross field validation with Hibernate Validator (JSR 303)
  • Java Bean Validation (JSR303) constraints involving relationship between several bean properties
like image 151
kevin847 Avatar answered Dec 14 '22 05:12

kevin847


Based on the number of times the question is displayed, I conclude that a lot of people still end up here looking for a validator for a date range.

Suppose we have a DTO containing another DTO (or class with @Embeddable annotation) with two fields with LocalDate (or other date representation, it's only example).

class MyDto {

    @ValidDateRange // <-- target annotation
    private DateRange dateRange;
    
    // getters, setters, etc.
}
class DateRange {

    private LocalDate startOfRange;
    private LocalDate endOfRange;

    // getters, setters, etc.
}

Now, we can declare our own @ValidDateRange annotation:

@Documented
@Constraint(validatedBy = DateRangeValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface ValidDateRange {

    String message() default "Start date must be before end date";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

Writing the validator itself also comes down to a few lines of code:

class DateRangeValidator implements ConstraintValidator<ValidDateRange, DateRange> {
    @Override
    public boolean isValid(DateRange value, ConstraintValidatorContext context) {
        return value.getStartOfRange().isBefore(value.getEndOfRange());
    }
}
like image 26
M. Dudek Avatar answered Dec 14 '22 03:12

M. Dudek