简体   繁体   中英

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. 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. Maybe is help, if i good understend your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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