Spring validator: Validating a list of nested objects
Just a code snippet on validating nested objects in java using Spring.
class MyForm() {
String myName;
List<TypeA> listObjects;
}
class TypeA() {
String number;
String value;
}
public class MyFormValidator implements Validator {
private TypeAValidator typeAValidator;
@Override
public boolean supports(Class clazz) {
return MyForm.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
MyForm myForm = (MyForm) target;
typeAValidator = new TypeAValidator();
int idx = 0;
for (TypeA item : myForm.getListObjects()) {
errors.pushNestedPath("listObjects[" + idx + "]");
ValidationUtils.invokeValidator(this.typeAValidator, item, errors);
errors.popNestedPath();
idx++;
...
}
...
}
}
public class TypeAValidator implements Validator{
@Override
public boolean supports(Class<?> clazz) {
return TypeA.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
TypeA objTypeA = (TypeA)target;
ValidationUtils.rejectIfEmpty(errors, "number", "number.notEmpty");
}
}