字符串形式的春季验证请求正文



我有一个端点,请求主体为String对象,其中包含一个电话号码:

@PostMapping("/phone-number") 
public Response phoneNumberRequest(@RequestBody @Valid @Pattern(regexp="myRegexp") String phoneNumber) {
...
}

我只有一个请求参数phoneNumber,所以我不需要JSON对象。我需要验证一个电话号码。但是当请求主体是简单的String对象时,@Valid注释不适用于@Pattern(regexp = "myRegexp")。所以我的问题是为什么?在这种情况下,我如何验证电话号码?

我建议如下:

@PostMapping("{phone-number}")
public Response phoneNumberRequest(
@PathVariable String phone-number) {
Boolean valid = phone-number.matches("your-regex");
...
}

最新更新