Search code examples
bean-validationhibernate-validator

Current datetime shouldnt pass the validation using @Past annotation


I need the @Past to error when the field is set to now. I realize that the now value on the field, and the now value used when the validator is comparing would be slightly different, thus the need to set the tolerance in hibernate validator.

Problem is that i can not get this to work. Here is the junit:

@Test
public void testHibernateValidator_withPast_withTodayDate() {
    // populates with 'now'
    MyFormWithPast form = new MyFormWithPast();
    form.setDt(OffsetDateTime.now(Clock.systemUTC()));

    ValidatorFactory factory = Validation.byProvider(HibernateValidator.class)
            .configure()
            .clockProvider(() -> Clock.systemUTC())
            // adds tolerance so that when comparing, the form dt and 'now' is considered equal, 
            //   therefore dt is not a past datetime
            .temporalValidationTolerance(Duration.ofMinutes(1))
            .buildValidatorFactory();

    Validator validator = factory.getValidator();
    Set<ConstraintViolation<MyFormWithPast>> errors = validator.validate(form);

    // needs to fail, since 'now' shouldn't be considered 'past'
    assertFalse("now shoudnt be considered as Past", errors.isEmpty());
}

public static class MyFormWithPast {
    @Past
    private OffsetDateTime dt;

    public void setDt(OffsetDateTime dt) {
        this.dt = dt;
    }

    public OffsetDateTime getDt() {
        return dt;
    }
}

I expect the validation to fail when i put in 'now' in the field, as 'now' shouldnt be considered as 'past'. What did i miss ?


Solution

  • The temporal validation tolerance was designed to be more lenient, not stricter. You want it to be stricter.

    I think you will need your own constraints to deal with what you want to do.