Spring Boot Validation with spring-boot-starter-validation is not working for Spring boot version 2.4.4

Viewed 4885

I was trying to validate a Request body in Spring boot and It's not working. Currently I'm using the Spring Boot 2.4.4 version. This is what I did.

I add this dependency spring-boot-starter-validation

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

The Controller with imported validation funcitons

import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;

@RestController
@RequestMapping("api/administration")
@Validated
public class AdminController {

    @PostMapping("/create-organization")
    @PreAuthorize("hasAuthority('all:write')")
    public ResponseEntity createNewOrganization(
            @Valid @RequestBody OrganizationDto organization) {

        Organization response = adminService.createNewOrganization(organization);

        HttpHeaders headers = new HttpHeaders();
        headers.add("Location", "/api/organization/" + response.getId().toString());

        return new ResponseEntity(headers, HttpStatus.CREATED);
    }
}

OrganizationDto

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;

@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@Builder
@ToString
public class OrganizationDto {

    @NotBlank
    @NotEmpty
    private String name;

    @NotBlank
    private String email;
}

The Problem I have is when I send the following body from Postman No error occurred.

{
    "name": "",
    "email": ""
}
3 Answers

Your code seems right and it should be working. So after that my advice would be:

1)Build the project with mvn clean install and try that jar that was built to see if it works

2)Or If you run it from Intelij

enter image description here

try to refresh maven dependencies and then run again

I suppose that you added later the dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

and it was not correctly plugged in the dependencies.

Using Springboot

Removing @RequestBody, and simply leaving @Valid was enough to get it to work.

sendEmail(@Valid SMTPEmail emailToSend) 

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.4</version>
    <relativePath/>
</parent>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>

Remove any hibernate-api and hibernate-validator dependencies.

You should be using @Validated instead of @Valid

public ResponseEntity createNewOrganization(
            @Validated @RequestBody OrganizationDto organization) {
}
Related