I want to know how to validate a list of nested objects in my form with Spring Validator (not annotation) in Spring MVC application.
class MyForm() {
St
You can use this anywhere in the project
import org.springframework.validation.ValidationUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.collections.CollectionUtils;
public static void invokeValidatorForNestedCollection(Validator validator,
Object obj,
String collectionPath,
Errors errors) {
Collection collection;
try {
collection = (Collection) PropertyUtils.getProperty(obj, collectionPath);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
throw new RuntimeException(e);
}
if (CollectionUtils.isEmpty(collection)) return;
int counter = 0;
for (Object elem : collection) {
errors.pushNestedPath(String.format(collectionPath + "[%d]", counter));
ValidationUtils.invokeValidator(validator, elem, errors);
errors.popNestedPath();
counter++;
}
}