Home > database >  Java Constructor Date type restrictions
Java Constructor Date type restrictions

Time:12-27

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "planDay")
@JsonIgnoreProperties(value = { "planDaysId" })
public class PlanDay {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long planDaysId;

    @Column
    @PastOrPresent
    @FutureOrPresent(groups = OneWeekInTheFuture.class)
    @Min(value = 2022 - 12 - 22, groups = OneWeekInTheFuture.class)
    @Max(value = 2022 - 12 - 29, groups = OneWeekInTheFuture.class)
    private LocalDate planDate;

    @Column
    private String weekday;

    @ManyToOne
    @JoinColumn(name = "planId", nullable = false)
    private Plans plans;

    @ManyToOne
    @JoinColumn(name = "medsId", nullable = false)
    private Meds meds;

    @Column
    private int medsToTake;
}

How can I change the @Min and @Max to be more dynamic, when the user inserts a date I want the @Min and the @Max to be 7 days later. Is it possible?

Like this, I have to insert it hardcoded every time.

CodePudding user response:

I suggest you write a custom validator as follows:

  1. Create a custom constraint annotation:
@Target({ FIELD })
@Retention(RUNTIME)
@Constraint(validatedBy = CustomDateValidator.class)
@Documented
public @interface CustomDate {

  String message() default "Invalid date!";

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

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

}
  1. Implement ConstraintValidator
class CustomDateValidator implements ConstraintValidator<CustomDate, LocalDate> {

  @Override
  public boolean isValid(LocalDate value, ConstraintValidatorContext context) {
    //You can write your own validation logic
    LocalDate startDate = LocalDate.now();
    LocalDate endDate = startDate.plusDays(7);
    return value.isAfter(startDate) && value.isBefore(endDate);
  }
}
  1. Annotate the field with the created constraint annotation
@CustomDate
private LocalDate planDate;

For reference: Validation with Spring Boot - the Complete Guide

  • Related