[英]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.我正在学习 Spring 引导 bean 验证,并希望在父实体中存在的 List 中实现自定义验证,以便发送更精确的错误作为响应。 Please suggest solution.Thanks in advance.
请提出解决方案。在此先感谢。
I have a Applicant Pojo class as follows我有一个申请人 Pojo class 如下
@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.地址 Class 如下。
@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 class 申请人的示例请求正文如下
{
"name":"hello",
"addresses":[{
"line1":"Line1",
"pinCode":"pinCode"
},
{
"line2":"Line2",
"pinCode":"pinCode"
}]
}
Output using default validation is as follows. Output 使用默认验证如下。
{
"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.我想实现自定义验证,例如 output 将如下所示。
{
"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. “Line2 is required in record 1 of addresses”表示地址 Json 数组中的记录 1 是强制性的,并且请求正文中不存在标记。
I have added the code in the repository - https://github.com/greenlearner01/rest-api-validation/tree/master/userManagementApp我已经在存储库中添加了代码 - 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.这里重要的是添加 @ControllerAdvice 来处理 ConstraintViolationException 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.