DEV Community

Shubham Bhati
Shubham Bhati

Posted on

Spring Boot Validation: Don't Reinvent the Wheel

You're building a new API endpoint and need to validate incoming request data. Most of us grab a bunch of if statements. Stop right there. Spring Boot's got your back with JSR 380 (Jakarta Bean Validation).

Just add the spring-boot-starter-validation dependency. Then, annotate your DTO with @Valid and your fields with constraints like @NotNull @Size(min=2 max=10) or @Email. Spring Boot automatically handles validation errors, returning a 400 Bad Request with details. It's way cleaner and more maintainable.

import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;

public class UserRequest {
    @NotBlank
    @Size(min = 2 max = 50)
    private String name;

    @NotBlank
    @Email
    private String email;

    // Getters and Setters
}
Enter fullscreen mode Exit fullscreen mode

Then in your controller:

@PostMapping("/users")
public ResponseEntity<?> createUser(@Valid @RequestBody UserRequest request) {
    // ... your logic
    return ResponseEntity.ok("User created");
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)