Posts

Showing posts with the label validation

JSR-303 and conditional validation with self-validation POJOs

The JSR-303 validation is great. Yes, really. But sometimes it is just too great. Imagine yourself having to do some complex validation on a single data-transfer POJO. Maybe you are collecting the data from a web-form and you need to show an error somewhere, but the default validation rules just don't fit, your to-be-enforced constraints are just too complex to be enforced using default constraints. It can be as simple as having to check for a string to be submitted, if, and only if, a checkbox is selected, but yet it is too complex to achieve using the default rules. Yes, you can define a custom annotation, write a validator, a unit-test for validator, then define a message for the validation error in your Validation.properties file and so on. Do you really have to do all that? If you are going to reuse the code – yes. But if it is really just a one-time shot? Then a simple short-cut can do the trick: just define a method in your POJO class that will do the validation, then an...