我在我的 Spring Controller 中使用 validator 。如果需要 @RequestParam
没有问题,我可以用 @NotBlank
检查 String。但是如果 @RequestParam
是可选的,我不能将它与 @NotBlank
一起使用,因为这个参数是可选的,有时可以为 null。
如果 String 不为空,我想验证 @NotBlank
。有什么约束可以帮助我吗?
@RequestParam @NotBlank String name
完美运行。我对 required=false
有疑问
如果客户端不发送可选的描述参数,则验证失败。
@PatchMapping("/role/{id}")
public ResponseEntity<?> updateRole(HttpServletRequest request, @PathVariable @Positive Integer id,
@RequestParam @NotBlank String name,
@RequestParam(required = false) @NotBlank String description)
如果描述不是null
,我想验证@NotBlank
。
`@RequestParam(required = false) @NotBlank String description`
如果我那样使用,我会收到“输入验证失败!”。
最佳答案
您需要为此添加自定义 validator 。
界面
@Documented
@Constraint(validatedBy = YourValidator.class)
@Target({ ElementType.METHOD,ElementType.ANNOTATION_TYPE,ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface NotBlankIfPresent{
String message() default "Error MEssage";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
您的 validator 类
public class YourValidator implements ConstraintValidator<NotBlankIfPresent, String> {
@Override
public boolean isValid(String s, ConstraintValidatorContext context) {
if (s == null) {
return true;
}
return !s.isBlank();
}
}
关于java - 如何验证非必需的 RequestParam 不为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54459882/