Validate a list of nested objects with Spring validator?

后端 未结 4 1450
别那么骄傲
别那么骄傲 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:25

    For the nested validation, you can do as below:

    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");
        }
    }
    

    Hope this helps.

提交回复
热议问题