SoFunction
Updated on 2025-03-08

How to solve the problem of invalid verification of @Valid object nested List object

introduction

When using Spring framework for data verification, sometimes you will encounter situations where the @Valid annotation cannot verify nested List objects.

This article will introduce the reasons for this problem and provide solutions to help you effectively verify nested List objects.

Problem background

Spring framework provides annotation-based data verification function, where @Valid annotation is used to mark objects that need to be checked.

However, when an object contains a nested List object, the outer layer cannot verify the nested List object using the @Valid annotation.

Cause analysis

By default, Spring framework supports nested objects with better verification, but for nested List objects, the @Valid annotation does not automatically recursively verify.

Controller is as follows:

public Objects flights(@RequestBody @Valid AForm aForm){
        return null;
    }

The Form is as follows:

public class AForm {

    @NotNull(message = "Required time for data update")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:")
    private Date updateTime;

    private List<ASubForm> updateList;
}

public class ASubForm {

    @NotBlank(message = "Flight number required")
    private String FlightNumber;

    @NotBlank(message = "Flight date required")
    private String FlightDate;

    @NotBlank(message = "Must choose from departure airports")
    private String DepAirport;

    @NotBlank(message = "Required airport for destination")
    private String ArrAirport;
}

question

When the controller is called, only the outer updateTime has prompted that the data update time is required, and the flight number, flight date, etc. are empty and the verification is not performed.

Solution

Modify AForm and add annotation to the list object and you can verify it normally

public class AForm {

    @NotNull(message = "Required time for data update")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:")
    private Date updateTime;

 	@Valid
    private List<ASubForm> updateList;
}

When using Spring framework for data verification, you can add @Valid annotation on nested List objects to enable recursive verification of nested objects. This way, the Spring framework automatically applies verification rules to each element in the List.

For example:

public class YourClass {
    @Valid
    private List<YourNestedClass> nestedList;
    // Other properties and methods}

By adding the @Valid annotation on the List object, the Spring framework automatically recursively checks the nested object and returns the verification result.

This approach is a simpler solution that avoids manual recursive verification or custom annotations and verification devices. It is recommended to prioritize the use of @Valid annotation on nested List objects to implement verification.

In addition to using @Valid annotation, there are other ways to verify nested List objects. Here are some alternatives:

1. Use a custom checker

You can write custom validators to handle nested List objects. Custom validators can implement verification logic for each element in the List and perform recursive verification.

First, create a custom verifier class:

public class ListValidator implements ConstraintValidator<ValidList, List<?>> {
    @Override
    public void initialize(ValidList constraintAnnotation) {
    }

    @Override
    public boolean isValid(List<?> list, ConstraintValidatorContext context) {
        if (list == null || ()) {
            return true; // No verification is performed on the empty list        }

        // Execute custom verification logic        for (Object element : list) {
            // Verify each element            // ...
        }

        return true; // Verification passed    }
}

Then, create a custom annotation to apply the verifier:

@Target({, })
@Retention()
@Constraint(validatedBy = )
public @interface ValidList {
    String message() default "Invalid list";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

Finally, use this annotation where nested List object verification is required:

public class YourClass {
    @ValidList
    private List&lt;YourNestedClass&gt; nestedList;
    // Other properties and methods}

With custom validators and annotations, you can implement verification logic for nested List objects.

2. Manual recursive verification

Another way is to manually recursively verify nested List objects. You can manually apply verification rules to each element of the List object in the verification object method.

public class YourClass {
    private List&lt;@Valid YourNestedClass&gt; nestedList;
    // Other properties and methods
    public void validate() {
        ValidatorFactory validatorFactory = ();
        Validator validator = ();
        for (YourNestedClass element : nestedList) {
            Set&lt;ConstraintViolation&lt;YourNestedClass&gt;&gt; violations = (element);
            // Handle verification errors        }
    }
}

By manually recursively verifying each element of a List object, you can implement verification of nested List objects.

These are some optional methods that can be used to verify nested List objects. You can choose the right solution for you based on your specific needs and circumstances.

Please note that the above method can also be used in conjunction with the @Valid annotation for more comprehensive verification.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.