如何在 Spring Boot 中使用正则表达式输入字段进行验证

5 regex spring spring-boot

我正在尝试在 Spring Boot 中仅对请求中的正数进行验证

\n
Public ResponseEntity getId(@RequestParam(value =\xe2\x80\x9cidPer\xe2\x80\x9d)@Pattern(regexp=\xe2\x80\x9c^[0-9]*$\xe2\x80\x9d),message = \xe2\x80\x9cthe value is negative\xe2\x80\x9d)\n@NotNull(message = \xe2\x80\x9cthe value is empty \xe2\x80\x9d) Long idPer){\n}\n
Run Code Online (Sandbox Code Playgroud)\n

在我的异常处理程序中我得到这个异常

\n
no validator could be found for constraint 'javax.validation.constraints.pattern' validatingtype long\n
Run Code Online (Sandbox Code Playgroud)\n

我的控制器类上面有@validated

\n

我究竟做错了什么?

\n

anu*_*ava 4

检查 的文档@Pattern。它适用于您在方法中使用的不允许的CharSequenceie bur。StringLong

您可以像这样重构您的代码:

public ResponseEntity getId (
        @Pattern(regexp="^[0-9]+$", message="the value must be positive integer")
        @RequestParam("idPer") final String idPerStr) {

    Long idPer = Long.valueOf(idPerStr);
    // rest of your handler here
}
Run Code Online (Sandbox Code Playgroud)

另请注意,这@NotNull不是必需的,因为我们使用的+量词仅允许模式中包含 1 个或多个数字。