Spring Boot Validation Java

Input Validation in Spring Boot: Different Ways to Do It

6 min read
January 20, 2025
Patrick Christen

Validating incoming API requests is one of the first steps to keep your Spring Boot applications safe and clean. Let's explore different approaches from simple annotations to complex custom validators.

Spring Boot integrates seamlessly with Jakarta Bean Validation (JSR-380), giving you powerful validation tools right out of the box. Whether you need basic field validation or complex business rules, there's an approach that fits your needs.

Validation in One Sentence

Spring Boot validation stops bad data at your API boundary before it reaches your business logic.

Let's dive deeper

Field-Level Validation

The most straightforward approach: apply annotations directly to your fields to enforce basic constraints like required values, format validation, and numeric ranges.

```java public class UserRequest { @NotBlank(message = "Name is required") private String name; @Email(message = "Must be a valid email") private String email; @Min(value = 18, message = "Age must be at least 18") private int age; } ```

And in your controller, add the @Valid annotation to trigger validation:

```java @PostMapping("/users") public ResponseEntity createUser(@Valid @RequestBody UserRequest request) { return ResponseEntity.ok("User created!"); } ```

Customizing Error Responses

By default, validation failures return lengthy stack traces. Clean this up with a global exception handler:

```java @RestControllerAdvice public class ValidationExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity> handleValidationErrors(MethodArgumentNotValidException ex) { Map errors = new HashMap<>(); ex.getBindingResult().getFieldErrors() .forEach(err -> errors.put(err.getField(), err.getDefaultMessage())); return ResponseEntity.badRequest().body(errors); } } ```

Now your API returns clean, user-friendly error messages:

```json { "name": "Name is required", "email": "Must be a valid email" } ```

Conditional Validation with @AssertTrue

Sometimes you need conditional logic: "if field A has this value, then field B must be set." Use @AssertTrue on a custom method:

```java public class UserRequest { private String role; private String adminCode; @AssertTrue(message = "adminCode is required when role=ADMIN") public boolean isValidAdmin() { if ("ADMIN".equals(role)) { return adminCode != null && !adminCode.isBlank(); } return true; } } ```

Spring calls isValidAdmin() automatically during validation. If it returns false, the request fails with your custom message.

Class-Level Custom Validator

For complex business rules that span multiple fields, create your own annotation and validator:

```java @Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy = RoleValidator.class) public @interface ValidUserRequest { String message() default "Invalid request"; Class[] groups() default {}; Class[] payload() default {}; } ```
```java public class RoleValidator implements ConstraintValidator { @Override public boolean isValid(UserRequest value, ConstraintValidatorContext context) { if ("ADMIN".equals(value.getRole()) && (value.getAdminCode() == null || value.getAdminCode().isBlank())) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate("adminCode required for role=ADMIN") .addPropertyNode("adminCode") .addConstraintViolation(); return false; } return true; } } ```

Apply the custom validator to your class:

```java @ValidUserRequest public class UserRequest { private String role; private String adminCode; } ```

Best Practices

"Good validation is like a good security guard—it stops problems at the door before they can cause damage inside."

Key Takeaways

Spring Boot's validation framework gives you multiple layers of protection. Start with simple field annotations for basic checks, then add conditional logic and custom validators as your business rules get more complex.

The key is to fail fast and fail clearly. Validate early, return meaningful error messages, and keep your business logic clean by ensuring only valid data reaches it.

👨‍💻

Patrick Christen

Full-stack engineer, MVP builder, and digital experimenter. I build things that solve real problems.

More Posts

What Is OAuth and How Does It Work?

Learn how OAuth authentication works behind the scenes with practical examples.

Available Now

Building MVPs That Matter

My approach to building minimal viable products that solve real problems. From idea to launch.

Coming Soon