Spring Boot request body validation not working

32 views Asked by At

Can anyone tell me what I am missing in this code? Spring Boot 3.2.3 and this dep is in place:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
@RestController
@Validated
public class TestController {

    @PostMapping("/test")
    public ResponseEntity<?> test(@Valid @RequestBody Test test) {

        System.out.println(test);

        return ResponseEntity.ok().build();
    }
}
@Valid
public class Test {

    @Valid
    @NotNull
    private String text;

    @Valid
    @NotNull
    public String getText() {
        return text;
    }

    @Valid
    @NotNull
    public void setText(@Valid @NotNull final String text) {
        this.text = text;
    }
}

I tried a dozen variants with the annotations but it still doesn't work. POST'ing this payload returns 200 OK:

{

}

or this

{
  "test": {
    
  }
}

or this

{
  "test": {
    "text": null
  }
}

Output on console: null

1

There are 1 answers

0
Faramarz Afzali On

Rewrite Test class as below.

import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;

public class Test {

    @NotEmpty
    @Size(min = 2, message = "should have at least 2 characters")
    private String text;

    public Test() {
    }

    public Test(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}

Then to customize the validation response can do as below.

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class ValidationHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {

            String fieldName = ((FieldError) error).getField();
            String message = error.getDefaultMessage();
            errors.put(fieldName, message);
        });
        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }
}

Tested with these inputs:

{
}

{
    "text":null
}

{
    "text":""
}

Response

{
    "text": "must not be empty"
}