Validate a list of nested objects with Spring validator?

后端 未结 4 1451
别那么骄傲
别那么骄傲 2020-12-29 05:38

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         


        
4条回答
  •  無奈伤痛
    2020-12-29 06:20

    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++;
        }
    }
    

提交回复
热议问题