使用多个注释验证RequestParam

问题描述 投票:0回答:0

我在 Spring Boot 3 的其余控制器中只有一个请求参数。 我添加了

@NotBlank
@Size
注释来验证该请求参数。 验证时,两个注释都会验证并随机提供两条消息的异常。

@RestController
@Validated
public class Controller {

  @PostMapping(LinkConfig.AUTH_REGISTER_URL)
  public ResponseEntity<?> post(@RequestParam
                                      @NotBlank(message = "Invalid Firstname: Firstname is empty.")
                                      @NotNull(message = "Invalid Firstname: Firstname is NULL.")
                                      @Size(min = 3, max = 20, message = "Invalid Firstname: Firstname must be of 3 - 30 characters.") String firstname) {
  }           
}

这将从 ConstraintViolationException 中给出此类消息

{
    "status": false,
    "message": [
        "registerUser.firstname: Invalid Firstname: Firstname must be of 3 - 30 characters., registerUser.firstname: Invalid Firstname: Firstname is empty."
    ]
}

但我想连续验证这些注释,即先

@NotBlank
然后验证后
@Size
第二次
@NotBlank

{
    "status": false,
    "message": [
        "registerUser.firstname: Invalid Firstname: Firstname is empty."
    ]
}

那么,

{
    "status": false,
    "message": [
        "registerUser.firstname: Invalid Firstname: Firstname must be of 3 - 30 characters."
    ]
}

我不想使用自定义类验证和分组。那么,我怎样才能实现这种类型的验证呢?请帮我解决这个问题。

java spring-boot annotations spring-validation
© www.soinside.com 2019 - 2024. All rights reserved.