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
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
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");
        }
    }
}