@Valid Not working @PostMapping spring boot


I am learning spring boot, I am adding Validation for @PostMapping, but somehow it always create a object even with non-valid value.


public class Hospital {
    private Integer id;
    @Size(min = 2)
    private String name;
    @Size(min = 2)
    private String city;

    public Hospital(Integer id, String name, String city) {
        this.id = id;
        this.name = name;
        this.city = city;


    HospitalData data;
    public ResponseEntity<Hospital> addHospital(@Valid @RequestBody Hospital hospital){
        Hospital newHospital = data.addHospital(hospital);

        URI location = ServletUriComponentsBuilder

        return ResponseEntity.created(location).build();



And previously I have added below dependency as I am using Spring 2.3.10 RELEASE, but it doesn’t work, so I have added above dependency.



I created a Test Application reproducing the state of your code. As stated under the comments, the code you provided should definitely work. You definitely don’t neet to provide a BindingResult to the method. Spring Boot throws a MethodArgumentNotValidException and therefore returns a bad request http status if the validation fails.

I created a project with following content:




public class DemoEntity {
    public String name;
    @Size(min = 3)
    public String greeting;


public class DemoController {
    public ResponseEntity<DemoEntity> put(@Valid @RequestBody DemoEntity demoEntity) {
        return ResponseEntity.ok(demoEntity);

Now, that’s what happens with my requests:

Name Greeting Result
Peter Mr 400
Stephen Monsieur 200
Clara null 200
Jenny Madamme 200

As you see from the table above, when greeting is null the result is an ok status. If you want to guarantee that the string is at least min characters long and not null, you need to declare this explicitely.

That’s, for example, if you want to validate optional fields like a mobile number. You know, it should be n numbers long and contain only numbers, but you don’t want to make it mandatory. Like I showed with the greeting above.

Answered By – Clijsters

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published