How to validate DateFields?

Hello,
I have two DateFields with startDate and endDate. How i can validate it in a way that you can not choose for endDate date before the startDate?

final DateField startDate = new DateField("Start date");
startDate.setRequired(true);
startDate.setValidationVisible(true);
startDate.setImmediate(true);
final DateField endDate = new DateField("End date");
endDate.setRequired(true);
endDate.setValidationVisible(true);
endDate.setImmediate(true);

Thank you!
BR,
Elena

Basically what you want to do is combine the two fields into one validator you add to to both fields:

Here is an example of a validator that takes two fields and validates them both:

class StartEndValidator implements Validator {

        private final DateField start, end;

        public StartEndValidator(DateField start, DateField end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public void validate(Object value) throws InvalidValueException {
            if (start.getValue() == null || end.getValue() == null) {
                return;
            }

            if (end.getValue().before(start.getValue())) {
                throw new InvalidValueException(
                        "End date cannot be before start date");
            }
        }
    }

Then you just add the validator to both fields like so:

startDate.addValidator(new StartEndValidator(startDate, endDate));
endDate.addValidator(new StartEndValidator(startDate, endDate));

Thank you John!

Now my application work properly :slight_smile:

BR,
Elena

This works fine but I do have a user form and there is Search button setup, validation only shows red into the End date field but it allow to search for it. Is there any way I can stop search option if the date is incorrect or end date is before begin date