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() { String myName; List<TypeA> listObjects; } class TypeA() { String number; String value; }
How can I create a MyFormValidator to validate the listObjects and add error message for number and value of TypeA.
The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.
@Validated annotation is a class-level annotation that we can use to tell Spring to validate parameters that are passed into a method of the annotated class. @Valid annotation on method parameters and fields to tell Spring that we want a method parameter or field to be validated.
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.
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"); } ... } ... } }
Interesting links :
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With