Search code examples
validationhibernate-validator

Can hibernate validator be used to validate a field depending on a field value from another class


I have a scenario where I need to validate some fields of a class depending on the value of a field from another class.

For ex: Street, City, Postal Code of Address class should not be null if the Employee has registered for a Group Retirement Plan.

Can this scenario be handled using Custom Validator of Hibernate Validator? Is this a good candidate for Hibernate Validator ? If so, could anyone provide me with some examples.

I have already gone through cross field validation examples like: Cross field validation with Hibernate Validator (JSR 303)

If I have a boolean indicator to indicate whether a user is registered for group retirement plan in Address domain class, I know I can come up with Custom Validator to verify the fields. But, I want to avoid adding indicator to Address class. As well, Address is not a field in Employee class to do nested validation.

The Frameworks I am using are Spring MVC and Mybatis for Data access. The validation is happening at Spring Rest API call with @Valid annotation.


Solution

  • I guess a custom class level constraint might work, but it depends on your actual domain classes. It is currently not clear how for example Employee, Group Retirement Plan and these other entities are connected.

    Whether Hibernate Validator is a good fit is whether you have other validations as well or which other frameworks are involved. For example, if you want validation to take place at JPA live cycle events, then Bean Validation is a good fit, since it integrates per specification with JPA. If you really only have this one validation, writing some custom code might be all you need.