0

I have a problem with validation.

I have two separate objects which are dates:

  1. LocalDateTime startDate
  2. LocalDateTime endDate

In the form, I do some validations, e.g. text length, etc. and everything is ok.

But I want to do a validation of two dates with each other, that is that date #2 can't be earlier than date #1.

I decided to use @AssertTrue.

But I want to have a message in the view after submitting the form with wrong dates, e.g. "The dates entered are wrong"

How to do it similar to e.g. validation related to the Name field. That when we do not enter, a message appears after sending the form that we need to correct (picture below) enter image description here

CreateEventForm

public class CreateEventForm {
    private Long id;
    @NotBlank(message = "Field title is required.")
    private String name;
    
    private LocalDateTime startDate;
    private LocalDateTime endDate;
    
    @AssertTrue(message = "Fields startindDateTime should be before than endingDateTime")
    private boolean isvalid() {
        return startingDateTime.isBefore(endingDateTime);
    }






I tried many ways but to no avail

1 Answers1

0

As you need to combine two fields in your validator, you need to write custom class-level constraint.

This answer can help: https://stackoverflow.com/a/2783859/4845935

dimnnv
  • 678
  • 3
  • 8
  • 21
  • thank you for your response. I did it. It works. But, I am using .html views (MVC/Thymeleaf) Can I somehow display a message on the form about e.g. an error if someone selects wrong dates? – Katie201 Dec 19 '22 at 20:01