Spring MVC @PathVariable上的多个javax.validation.约束验证

niwlg2el  于 2022-11-14  发布在  Spring
关注(0)|答案(1)|浏览(213)

I am applying multiple validations on path variable

@PathVariable(name = "id")
  @NotBlank(message = "Missing required field")
  @Size(min = 1, max = 3, message = "Invalid input size")
String id

Now, when I am sending empty string in path param then I am getting both messages because both validations are failing.
For my param id, I want both validations but it should not throw both error messages at a time when I am sending empty string.
I want it to throw only
"Missing required field"
and not both.

wgeznvg7

wgeznvg71#

NotBlankNotNullNotEmpty验证的两个功能的组合。因此,当绑定的pathVariable为nullempty时,@NotBlank都将触发。
因为您已经有@Size(min = 1, max = 3, message = "Invalid input size"),所以您已经在检查not empty。如果pathVariable是empty字串,这个注解会与@NotBlank同时触发。
因此,当它是null时,您只需要一个不同的约束验证,这样强制约束的两个注解就不会相互覆盖。
作为解决方案,您可以将@NotBlank替换为@NotNull

@PathVariable(name = "id")
  @NotNull(message = "Missing required field")
  @Size(min = 1, max = 3, message = "Invalid input size")
String id

相关问题