简体   繁体   中英

How to validate List<Object> such that all the data member is present in the request using javax.validation?

I'm learning the Spring Boot bean validation and wanted to implement custom validation in List present in the parent entity in such as way that more precise error is sent in response. Please suggest solution.Thanks in advance.

I have a Applicant Pojo class as follows

@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Applicant{
    @NotEmpty (message="name is mandatory")
    private String name;
    @NotEmpty (message="addresses is mandatory")
    @Valid
    private List<Address> addresses;
}

Address Class is as follows.

@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Address{
    @NotEmpty  (message="Line1 is mandatory")
    private String line1;
    @NotEmpty (message="Line2 is mandatory") 
    private String line2;
    @NotEmpty (message="pinCode is mandatory")
    private String pinCode;
}

Sample Request body for the class Applicant is as follows

{
  "name":"hello",
  "addresses":[{
    "line1":"Line1",
    "pinCode":"pinCode"
  },
  {
    "line2":"Line2",
    "pinCode":"pinCode"
  }]
}

Output using default validation is as follows.

{
    "timestamp": "2020-08-15T09:29:30.807+0000",
    "status": 400,
    "errors": [
        "Line2 is mandatory",
        "Line1 is mandatory"
    ]
}

I want to implement custom validation is such as way that the output will be as follows.

{
    "timestamp": "2020-08-15T09:29:30.807+0000",
    "status": 400,
    "errors": [
        "Line2 is mandatory in record 1 of addresses",
        "Line1 is mandatory in record 1 of addresses"
    ]
}

"Line2 is mandatory in record 1 of addresses" will indicate that the record 1 in Address Json Array is mandatory and the tag is not present in the request body.

I have added the code in the repository - https://github.com/greenlearner01/rest-api-validation/tree/master/userManagementApp

Now the error message will look like below(it's not exactly same as you asked for but I think very close)-

 {
   "status": "BAD_REQUEST",
   "errors": [
     "addresses[2].line1:must not be null",
     "addresses[2].line2:must not be null",
     "addresses[0].line1:must not be null",
     "addresses[1].line2:must not be null"
   ],
   "timestamp": "2020-08-15T17:52:31.138",
   "path": "uri=/user"
 }

Here Important thing is to add the @ControllerAdvice where the ConstraintViolationException is taken care of.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM