gpt4 book ai didi

java - 为列表中的特定元素设置 ValidationError 消息

转载 作者:行者123 更新时间:2023-12-01 18:07:03 26 4
gpt4 key购买 nike

目前,我正在 Play 框架 Java 中实现自定义验证。我有一个包含元素列表的类:

public class StandardRequest{
...
private List<@Valid StandardMaterial> materials;
...
//getters setters

StandardMaterial 类内部有一个验证逻辑:

@Validate
public class StandardMaterial extends Material implements Validatable<ValidationError> {
private Integer condition_value;
...
@Override
public ValidationError validate() {
if(condition_value < 0 || condition_value > 100){
return new ValidationError("materials","must be integer between 0 and 100");
}

上述类的输入json是这样的:

"materials": [{"material_number": "1", "condition_type":"A1","condition_value": "-15"},
{"material_number": 2","condition_type":"A2","condition_value": "-25"}]

这会产生一条验证错误消息作为响应,如下所示:

 "validations": [
{
"property": "materials",
"message": "must be integer between 0 and 100"
},
{
"property": "materials",
"message": "must be integer between 0 and 100"
}
],

我现在无法实现指定 Material 的索引,我需要得到这个响应:

"validations": [
{
"property": "materials[0]",
"message": "must be integer between 0 and 100"
},
{
"property": "materials[1]",
"message": "must be integer between 0 and 100"
}
],

Any ideas how can I do that?
Thanks in advance

最佳答案

<强>1。编辑您的 StandardMaterial 类,如下所示

import javax.validation.constraints.Min;
import javax.validation.constraints.Max;

public class StandardMaterial {

@Size(value=0,message="must be greater than or equal to 0")
@Size(value=100,message="must be less than or equal to 100")
private Integer condition_value;

}

<强>2。使用 @RestControllerAdvise 创建单独的类来处理全局任何类中的此类错误

@RestControllerAdvice
public class GlobleExceptionHandler extends ResponseEntityExceptionHandler{

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {

//Get All Errors
List<FieldError> errors = ex.getBindingResult().getFieldErrors();

//Iterate and add to your custom object
for(FieldError e:errors){
e.getDefaultMessage();//Your Error Message
e.getField();//Field Name with index
}

}

}

这样你就可以做到......我没有展示所有内容......但你会知道如何做。

关于java - 为列表中的特定元素设置 ValidationError 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60542926/

26 4 0
文章推荐: java - 在 ubuntu 15.10 上安装 Java
文章推荐: perforce - p4sync,如何在使用通配符时排除文件?
文章推荐: ruby-on-rails - 重用 RSpec 行为验证
文章推荐: java - Streams API::如何从 LIST 修改自定义对象的变量?