简体   繁体   English

Spring 验证请求正文为字符串

[英]Spring validation request body as string

I have endpoint with request body as String object, which contains a phone number:我有一个请求正文为String object 的端点,其中包含一个电话号码:

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

I have just one request parameter phoneNumber , so I don't need a JSON object.我只有一个请求参数phoneNumber ,所以我不需要 JSON object。 I need to validate a phone number.我需要验证电话号码。 But @Valid annotation doesn't work with @Pattern(regexp = "myRegexp") when request body is the simple String object.但是当请求正文是简单的String @Valid时,@Valid 注释不适用于@Pattern(regexp = "myRegexp") So my question is why?所以我的问题是为什么? How can I validate phone number in this case?在这种情况下如何验证电话号码?

I would suggest the following:我建议如下:

@PostMapping("{phone-number}")
public Response phoneNumberRequest(
  @PathVariable String phone-number) {

  Boolean valid = phone-number.matches("your-regex");
  ...

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM