Clarification required on Spring Boot validator

175 views Asked by At

Folks, I have a project in SpringBoot 3.2.2 and am trying to add validators (@NotEmpty) to the input - but, it doesn't seem to work. Here are the things that I have already done / tried.

  1. Added the following dependency

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

Note: I also tried with hibernate-validator dependency as well - but, no luck there as well

  1. I added @Validated annotation to my controller + @Valid annotation to the parameter - highlighted below in the code

    @RestController
    @Validated
    @RequestMapping("/api/posts")
    public class PostController {
        private PostService postService;
    
        public PostController(PostService postService) {
            this.postService = postService;
        }
    
        @PostMapping
        public ResponseEntity<PostDto> createPost (@Valid @RequestBody PostDto postDto) {       
            return new ResponseEntity<>(postService.createPost(postDto), HttpStatus.CREATED);
        }
    
  2. In my DTO class, I added the @NotEmpty annotation - importing the jakarta.validation.constraints. I read that the javax.validation.constraints doesn't work for SpringBoot projects greater than 3.x version.

    import jakarta.validation.constraints.NotEmpty;
    public class PostDto {
        private Long id;
    
        @NotEmpty (message = "Title cannot be empty")
        private String title;
    

I also tried with hibernate-validator dependency as well - but, no luck there as well.

Thanks in advance!

0

There are 0 answers