JSR 303 Validation, If one field equals "something", then these other fields should not be null

Eric picture Eric · Feb 14, 2012 · Viewed 101.2k times · Source

I'm looking to do a little custom validation with JSR-303 javax.validation.

I have a field. And If a certain value is entered into this field I want to require that a few other fields are not null.

I'm trying to figure this out. Not sure exactly what I would call this to help find an explanation.

Any help would be appreciated. I am pretty new to this.

At the moment I'm thinking a Custom Constraint. But I'm not sure how to test the value of the dependent field from within the annotation. Basically I'm not sure how to access the panel object from the annotation.

public class StatusValidator implements ConstraintValidator<NotNull, String> {

    @Override
    public void initialize(NotNull constraintAnnotation) {}

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if ("Canceled".equals(panel.status.getValue())) {
            if (value != null) {
                return true;
            }
        } else {
            return false;
        }
    }
}

It's the panel.status.getValue(); giving me trouble.. not sure how to accomplish this.

Answer

Audrius Meskauskas picture Audrius Meskauskas · Jun 10, 2016

Define method that must validate to true and put the @AssertTrue annotation on the top of it:

  @AssertTrue
  private boolean isOk() {
    return someField != something || otherField != null;
  }

The method must start with 'is'.