0

i have a class which is working as the request payload for my api . I need to validate the one of my field "dateOfBirth". Using the javax.validation.past i am checkking the date is not future date but i also want to validate that the date must not be less than 1900-01-01 .

Is there any way using javax.validation api we can do it?

Class Employee{

 ----
 ---
  @Past(message="date of birth must be less than today")  
  @DateTimeFormate( pattern="yyyy-MM-dd")
  private Date dateOfBirth;

  //constuctor

  //getter & setter

}
Naman
  • 27,789
  • 26
  • 218
  • 353
Prabhat Yadav
  • 1,181
  • 6
  • 18
  • 29
  • You can look more into *how to define custom validations and use annotations for them*. – Naman Jan 18 '19 at 16:23
  • FYI, the terrible `Date` class was supplanted years ago by the modern *java.time* classes with the adoption of JSR 310. Specifically, `Instant`. The modern classes use sane counting for the year and the month, unlike the legacy classes. For a date-only value without time-of-day and without time zone, use `LocalDate`. – Basil Bourque Jan 18 '19 at 17:28

2 Answers2

1

You should define custom annotation for this propose. something like bellow:

@Target(ElementType.FIELD)
@Retention(RUNTIME)
@Constraint(validatedBy = DateValidator.class)
@Documented
public @interface IsAfter{
   String message() default "{message.key}";
   String current();
}

and also define a custom validator like this:

public class DateValidator implements ConstraintValidator<IsAfter, LocalDate> {

String validDate;

@Override
public void initialize(IsAfter constraintAnnotation) {
    validDate = constraintAnnotation.current();
}

@Override
public boolean isValid(LocalDate date, ConstraintValidatorContext constraintValidatorContext) {
    String[] splitDate = validDate.split("-");
    return date.isAfter(LocalDate.of(Integer.valueOf(splitDate[0]), Integer.valueOf(splitDate[1]), Integer.valueOf(splitDate[2])));
  }
}

and use this annotation:

@Past(message="date of birth must be less than today")  
@IsAfter(current = "1900-01-01")
@DateTimeFormate( pattern="yyyy-MM-dd")
private Date dateOfBirth;

note: I haven't tested this annotation!

Hadi J
  • 16,989
  • 4
  • 36
  • 62
0

The post from https://stackoverflow.com/a/54258098/15541786 is great. I did it in my project and it's working. Just to avoid errors in console, add also to interface

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

So, working example:

@Target(ElementType.FIELD)
@Retention(RUNTIME)
@Constraint(validatedBy = DateValidator.class)
@Documented
public @interface IsAfter{
   String message() default "{message.key}";
   String current();
   Class<?>[] groups() default {};
   Class<? extends Payload>[] payload() default {};
}