conquester
conquester

Reputation: 1132

Spring Boot REST Validation fails for every request

I have implemented Request validation in a REST Spring Boot API.

Here is the request model:

@Data
@ApiModel
public class ConfirmUserTokenRequest {
    @Min(3)
    @Max(25)
    @NotBlank
    private String firstName;

    @Min(3)
    @Max(25)
    @NotBlank
    private String lastName;

    @Email
    @NotBlank
    private String email;

    @Min(3)
    @Max(50)
    private String companyName;

    @ApiModelProperty(value = "Usage purpose", allowableValues = "SEO, CRAWLING, BLOGGING, DEVOPS, OTHER")
    private String usagePurpose;

    @Min(2)
    @Max(2)
    @ApiModelProperty(value = "ISO Alpha-2 country code of user", example = "US")
    private String countryCode;

    @Min(6)
    @Max(30)
    @NotBlank
    private String password;

    @NotBlank
    private String redirectUri;

    private String data;
}

In the controller method, I have validated the request body parameter with *@Valid* annotation to turn on validation.

Here is the controller method definition:

@PostMapping
@ResponseStatus(HttpStatus.NO_CONTENT)
public ResponseEntity<Object> createToken(@Valid @RequestBody ConfirmUserTokenRequest confirmUserTokenRequest)

Here is the controller advise to handle validation exception:

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  HttpHeaders headers, HttpStatus status,
                                                                  WebRequest request) {
        List<String> errors = new ArrayList<>();
        for (FieldError error : ex.getBindingResult().getFieldErrors()) {
            errors.add(error.getField() + ": " + error.getDefaultMessage());
        }
        for (ObjectError error : ex.getBindingResult().getGlobalErrors()) {
            errors.add(error.getObjectName() + ": " + error.getDefaultMessage());
        }
        APIError apiError = new APIError( "Validation failed", errors);
        return new ResponseEntity<>(apiError, HttpStatus.BAD_REQUEST);
    }

The validation exception is being thrown even for seemingly valid requests: For example, the following request gives a validation error:

POST /no-auth/manager/token/confirm-user HTTP/1.1

Host: 127.0.0.1:8080
Content-Type: application/json
cache-control: no-cache
{
"firstName": "John",
"lastName": "Doe",
"email": "[email protected]",
"countryCode": "AU",
"companyName": "Galaxy Corp",
"usagePurpose": "SEO",
"password": "init@test",
"data": null,
"redirectUri": "http://127.0.0.1:8080/callback/confirm-user"
}

I get the following validation error:

{
    "timestamp": "2019-01-09T06:54:56.635",
    "message": "Validation failed",
    "errors": [
        "companyName: must be greater than or equal to 3",
        "password: must be less than or equal to 30",
        "lastName: must be less than or equal to 25",
        "firstName: must be less than or equal to 25",
        "lastName: must be greater than or equal to 3",
        "password: must be greater than or equal to 6",
        "firstName: must be greater than or equal to 3",
        "companyName: must be less than or equal to 50"
     ]
}

Even for this seemingly valid requests, errors are being thrown. What is going wrong?

Upvotes: 0

Views: 940

Answers (1)

swayamraina
swayamraina

Reputation: 3158

Instead of using @Min & @Max separately, try @Size(min = 2, max = 25).

Also, if you have applied @Min there is no need for @NotBlank change it to @NotNull

@Min and @Max are used for validating numeric fields like int, short, byte etc and their respective primitive wrappers.

@Size is used to check the length constraints on the fields.

As per documentation, @Size supports String, Collection, Map and arrays while @Min and @Max supports primitives and their wrappers.

Upvotes: 2

Related Questions