In Spring Boot, you can use annotations from the javax.validation or jakarta.validation packages (depending on the version of Spring Boot you are using) to validate fields in your Java classes. These annotations are commonly used in conjunction with the Bean Validation API (JSR 380). Here are some of the most commonly used validation annotations:
1. @NotNull
:
Ensures that the annotated field is not null
.
@NotNull(message = "Name cannot be null")
private String name;
2. @NotEmpty
:
Ensures that the annotated field is not null
and not empty (applies to strings, collections, maps, and arrays).
@NotEmpty(message = "Name cannot be empty")
private String name;
3. @NotBlank
:
Ensures that the annotated string field is not null
,
not empty, and not only whitespace.
@NotBlank(message = "Name cannot be blank")
private String name;
4. @Size
:
Specifies the size constraints for a string, collection, map, or array.
@Size(min = 2, max = 30, message = "Name must be between 2 and 30 characters")
private String name;
5. @Min
and @Max
: Specifies the
minimum and maximum values for numerical fields.
@Min(value = 18, message = "Age must be at least 18")
@Max(value = 100, message = "Age must be less than or equal to 100")
private
int age;
6. @DecimalMin
and @DecimalMax
: Specifies
the minimum and maximum values for BigDecimal
or double
fields.
@DecimalMin(value = "0.0", inclusive = true, message = "Price must be positive")
private BigDecimal price;
7. @Positive
and @Negative
: Ensures that
a number is strictly positive or negative.
@Positive(message = "Amount must be positive")
private
int amount;
Advanced Validations
1. @Email
:
Validates that a field is a well-formed email address.
@Email(message = "Email should be valid")
private String email;
2. @Pattern
:
Specifies a regular expression that the field must match.
@Pattern(regexp = "^[A-Za-z0-9]+$", message = "Username must be alphanumeric")
private String username;
3. @Future
and @Past
: Validates that a
date is in the future or past, respectively.
@Future(message = "Event date must be in the future")
private LocalDate eventDate;
@Past(message = "Date of birth must be in the past")
private LocalDate dateOfBirth;
4. @AssertTrue
and @AssertFalse
: Ensures that
a boolean field is true or false, respectively.
@AssertTrue(message = "Must agree to terms")
private
boolean agreedToTerms;
@Valid
Annotation
Purpose: The @Valid
annotation is used to trigger validation of a bean in Spring Boot. It is
typically used in combination with JSR 380 (Bean Validation 2.0) annotations to
ensure that input data meets specified constraints.
Usage: @Valid
is commonly applied to method parameters in controller classes or service
methods to validate the input data. Spring Boot’s validation mechanism
automatically checks constraints defined using annotations such as @NotNull
,
@Size
, @Email
,
etc.
Syntax
and Example
1. Validation
in a Controller:
@RestController
public
class
UserController {
@PostMapping("/users")
public User
createUser(@Valid @RequestBody User user) {
// The @Valid annotation ensures that the 'user' object is validated
// according to constraints defined in the User class.
return userService.save(user);
}
}
2. User
Class with Validation Annotations:
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public
class
User {
@NotBlank(message = "Username cannot be blank")
@Size(min = 3, max = 50, message = "Username must be between 3 and 50 characters")
private String username;
@NotBlank(message = "Password cannot be blank")
private String password;
// Getters and setters
}
Key
Points:
@Valid
: Triggers validation based on JSR 380 annotations. If validation fails, an exception (e.g.,MethodArgumentNotValidException
) will be thrown, which can be handled to return appropriate error responses.- Validation Constraints: Use
standard validation constraints (e.g.,
@NotNull
,@Size
,@Email
) in your model or DTO classes to specify validation rules.
No comments:
Post a Comment