0

I'm trying to write some validation annotations for a Spring project.

I have several fields which are nullable, unless the value of a bool (in the same object) is true.

Is there some easy way to do something like:

@NotNull(if xyz=true)

? Thanks

  • Not sure, but I think you can't do that with annotations and have to use valodator. – Evgeni Dimitrov Nov 15 '13 at 14:43
  • You're going to have to use a custom constraint and validator. – Vivin Paliath Nov 15 '13 at 14:54
  • possible duplicate of [JSR 303 Validation, If one field equals "something", then these other fields should not be null](http://stackoverflow.com/questions/9284450/jsr-303-validation-if-one-field-equals-something-then-these-other-fields-sho) – Vivin Paliath Nov 15 '13 at 15:00
  • @ Vivin Paliath Yes this is duplication. @Gareth Johnson You need to perform cross field validation with custom class-level constraint. – mvb13 Nov 15 '13 at 15:03

1 Answers1

0

I think it's not possible to do with annotations (too complex), but this can be done fairly easy by implementing org.springframework.validation.Validator interface:

public class MyClassValidator implements Validator {
    @Override
    public boolean supports(Class c) {
        return MyClass.class.equals(c);
    }

    @Override
    public void validate(Object object, Errors errors) {
        MyClass myClass = (MyClass) object;

        if (myClass.getA() == null) {
            errors.rejectValue("avalue", "avalue.empty", "'A' value cannot be empty");
        }
        else if (myClass.getA() == true && (myClass.getB() == null || myClass.getB() < 0)) {
            errors.rejectValue("bvalue", "bvalue.notvalid", "'B' value is not valid");
        }
    }
}
maxnx
  • 106
  • 3