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.
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
I added
@Validatedannotation to my controller +@Validannotation 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); }In my DTO class, I added the
@NotEmptyannotation - importing the jakarta.validation.constraints. I read that thejavax.validation.constraintsdoesn'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!