使用Spring验证器验证嵌套对象的列表?

2022-09-02 02:48:06

我想知道如何在Spring MVC应用程序中使用Spring Validator(不是注释)来验证表单中的嵌套对象列表。

class MyForm() {
    String myName;
    List<TypeA> listObjects;
}
class TypeA() {
    String number;
    String value;
}

如何创建MyFormValidator来验证列表对象并为TypeA的数量和值添加错误消息。


答案 1

对于嵌套验证,可以执行以下操作:

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

希望这有帮助。


答案 2
public class MyFormValidator implements Validator {

    @Override
    public boolean supports(Class clazz) {
        return MyForm.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        MyForm myForm = (MyForm) target;

        for (int i = 0; i < myForm.getListObjects().size(); i++) {
            TypeA typeA = myForm.getListObjects().get(i);

            if(typeAHasAnErrorOnNumber) {
                errors.rejectValue("listObjects[" + i + "].number", "your_error_code");
            }

            ...
        }

        ...
    }

}

有趣的链接 :


推荐