简体   繁体   English

Spring MVC 验证:只需要一个字段

[英]Spring MVC validation: Only one field is required

I am creating a new endpoint in this API, which accepts a request containing either a username or a 5 or 9-digit phone number.我正在此 API 中创建一个新端点,它接受包含用户名或 5 位或 9 位电话号码的请求。 I need to add validations to validate the request to contain either a username OR phone number;我需要添加验证来验证包含用户名或电话号码的请求; if both are provided then return a validation error.如果两者都提供,则返回验证错误。 Here is the current code I have.这是我拥有的当前代码。

    @GetMapping("/users")
    @Operation(summary = "API to return users based on username or phone number")
    public ResponseEntity<List<UserResponseObject>> usersByNameOrNumber(
            @Valid @RequestParam(name = "phone-number", required = false) @Pattern(regexp = "^(\\d{5}|\\d{9})$") String userPhoneNumber,
            @Valid @PathVariable(name = "user-name", required = false) @Pattern(regexp = "^[a-zA-Z ]*$") String userName) {

            try {
                    ...
            } catch (Exception e) {
                    ...
            }
    }

How can I modify this block to meet the requirements?如何修改此块以满足要求? Currently, both fields are tagged as not required and there is no validation in place.目前,这两个字段都被标记为不需要,并且没有进行验证。 I'd like it require ONLY one of these fields to be not null.我希望它只需要这些字段之一不为空。

Try use optional, i dont know how solution you need.尝试使用可选,我不知道你需要怎样的解决方案。

@GetMapping("/users")
                @Operation(summary = "API to return users based on username or phone number")
                public ResponseEntity<List<UserResponseObject>> usersByNameOrNumber(
                        @Valid @RequestParam(value = "phoneNumber", required = false) @Pattern(regexp = "^(\\d{5}|\\d{9})$") Optional<String> phoneNumber,
                        @Valid @RequestParam(value = "userName", required = false) @Pattern(regexp = "^[a-zA-Z ]*$") Optional<String> userName) {
            
                        try {
                                        if(phoneNumber.isPresent()){} 
                                        if(userName.isPresent()){} 
                        } catch (Exception e) {
                                
                        }
                }

But i'm not sure the @Pattern and Optional will be work good, but probably yes.但我不确定 @Pattern 和 Optional 是否会正常工作,但可能是的。 Maybe is help, if i good understend your problem.也许是帮助,如果我很好理解你的问题。

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

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