I'm working with Java validation and Spring. I have several classes that need validation set up. When it comes to validating simple fields of each class, my validators work fine. However, the field for one class contains a List of two other classes I need validated, and one of those contains a list of two other classes I need validated.
I found a way to get this working, but it is a bit messy and requires (what I think) is too much extra code in my Controller. For example, I made a separate method in my validation to validate the list of Class A:
public Errors validateClassA(ClassA classA){
List<ClassB> classBs = classA.getScanResults().getClassesToValidate();
for (ClassB classB : classBs) {
Errors error = new BeanPropertyBindingResult(classB, "ClassB");
classBValidator.validate(classB, error);
if(error.hasErrors()){
return error;
}
}
return null;
}
This works just for testing, but I don't want to pass back a null value and it seems a little bit messy. Here's the portion of my Controller using this code:
classAValidator.validate(classA, bindingResult);
Errors classBErrors = classAValidator.validateClassB(classA);
if (bindingResult.hasErrors()) {
classAValidator.logErrors(bindingResult);
return new ResponseEntity<GenericServiceResponse<Void>>(new GenericServiceResponse<Void>(FAIL, bindingResult.toString()), HttpStatus.BAD_REQUEST);
}
if(classBErrors.hasErrors()){
classAValidator.logErrors(classBErrors);
return new ResponseEntity<GenericServiceResponse<Void>>(new GenericServiceResponse<Void>(FAIL, classBErrors.toString()), HttpStatus.BAD_REQUEST);
}
Feels like I'm making this more complicated than it needs to be, but I'm not sure how to approach it. From a brief glance at the documentation for the Errors class, it looks like there is some way to set nested routes for the errors, but I couldn't seem to find many examples of that so I'm not sure if it would apply in my situation. Hope all of this makes sense and thanks for any suggestions.