Introduction
Input validation helps keep your app safe and working well by checking user data before using it.
Jump into concepts and practice - no test required
Input validation helps keep your app safe and working well by checking user data before using it.
@Valid
public ResponseEntity<?> methodName(@Valid @RequestBody DataClass data) {
// method code
}public class User { @NotNull @Size(min = 2, max = 30) private String name; @Email private String email; }
@PostMapping("/addUser") public ResponseEntity<String> addUser(@Valid @RequestBody User user) { return ResponseEntity.ok("User added"); }
This Spring Boot controller defines a User class with validation rules. The addUser method checks the input before accepting it.
import jakarta.validation.Valid; import jakarta.validation.constraints.*; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController public class UserController { public static class User { @NotNull(message = "Name cannot be null") @Size(min = 2, max = 30, message = "Name must be 2-30 characters") private String name; @Email(message = "Email should be valid") private String email; // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } @PostMapping("/users") public ResponseEntity<String> addUser(@Valid @RequestBody User user) { return ResponseEntity.ok("User " + user.getName() + " added successfully"); } }
Always provide clear error messages for invalid input to help users fix mistakes.
Input validation protects your app from crashes and security risks.
Combine validation with exception handling to manage invalid inputs gracefully.
Input validation checks user data to keep apps safe and stable.
Use annotations like @Valid, @NotNull, and @Email in Spring Boot.
Validate inputs before processing or saving data.
@PostMapping("/register")
public ResponseEntity<String> registerUser(@Valid @RequestBody User user) {
return ResponseEntity.ok("User registered");
}user object has an invalid email format and @Email is used on the email field?public class User {
@NotNull
private String name;
@Email
private String email;
// getters and setters
}