Accessing the main object in a javax.validation.ConstraintValidator

2.4k views Asked by At

I'm trying to use the javax.validation framework for a all the web app's validation needs. In order to do this, I need to write some validators that access the main object being validated. For example, let's say my object has startDate and endDate and I need to validate to make sure that startDate is not greater than endDate. Or any other scenario where one field's validation depends on the contents of another field inside the main object.

My question is: how do I get to those other fields, or to the main object itself from the validator. I have a feeling I might be able to get to it via constraintValidatorContext, but haven't yet figured out how.

I'm using the following for writing custom validators: https://docs.jboss.org/hibernate/validator/4.1/reference/en-US/html/validator-customconstraints.html

Is ConstraintValidator even the right tool for the job here? Basically, my end goal is to have all validation happen by just looping through validators like this:

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<MyClass>> violations = validator.validate(myObject);

    for(ConstraintViolation<MyClass> validation : violations)
    {
        // put error message in a collection to display in the jsp
    }

And not have a whole string of if/elses or try/catches in the validate method that are checking each field.

Also, my project does not use any frameworks like Hybernate or Spring, and I can't really integrate them into it at this point. It's just a standard Servlet/jsp project.

1

There are 1 answers

0
JB Nizet On BEST ANSWER

If the validator is supposed to validate two related fields of an object at once, it should validate the object itself, and not one field of the object. And the corresponding annotation should be on the class, and not on a field of the class.