Hackforge Academy

Category: java

valid annotation in spring boot

Published on 22 Apr 2026

Explanation

@Valid annotation in Spring Boot is used to validate incoming request data automatically based on validation rules defined in the model class.

Code:

@PostMapping("/users")
public ResponseEntity<String> 
createUser(@Valid @RequestBody User user) {
  return ResponseEntity.ok("User is valid");
}

Explanation

Validation rules are defined inside the entity class using annotations like @NotNull, @NotBlank, @Size, and @Email.

Code:

public class User {

  @NotBlank(message = "Name is required")
  private String name;

  @Email(message = "Invalid email format")
  private String email;
}

Explanation

If validation fails, Spring Boot automatically returns a 400 BAD REQUEST response unless custom exception handling is implemented.

Code:

// Example error response:
// 400 Bad Request
// "Name is required"

Explanation

@Valid works with @RequestBody, @PathVariable, and @ModelAttribute to validate different types of request inputs.

Code:

public ResponseEntity<String> 
updateUser(
@Valid @ModelAttribute User user) {
  return ResponseEntity.ok(
"Validated successfully");
}

Explanation

Use BindingResult along with @Valid to capture validation errors manually instead of returning default error responses.

Code:

public ResponseEntity<String> 
saveUser(@Valid @RequestBody User user,
 BindingResult result) {
  if (result.hasErrors()) {
    return ResponseEntity.badRequest().
body("Validation failed");
  }
  return ResponseEntity.ok(
"User saved successfully");
}

Explanation

Common validation annotations include @NotNull, @NotBlank, @Size, @Min, @Max, and @Email for enforcing input constraints in REST APIs.

Code:

public class Product {

  @NotNull
  private String name;

  @Min(1)
  private int price;
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community