Common Data Validation Annotations in Spring MVC
Annotation | Description |
---|---|
@NotNull |
Validates that the annotated element is not null. |
@NotEmpty |
Validates that the annotated element is not empty (not null and size > 0). |
@NotBlank |
Validates that the annotated string is not empty and contains at least one non-whitespace character. |
@Min(value) |
Validates that the annotated element’s value is greater than or equal to the specified minimum value. |
@Max(value) |
Validates that the annotated element’s value is less than or equal to the specified maximum value. |
@Size(min=, max=) |
Validates that the annotated element’s size is within the specified range (for strings, this is length; for collections, this is size). |
@Email |
Validates that the annotated element is a valid email address. |
@Positive |
Validates that the annotated element’s value is a positive number (greater than 0). |
@PositiveOrZero |
Validates that the annotated element’s value is a non-negative number (greater than or equal to 0). |
@Negative |
Validates that the annotated element’s value is a negative number (less than 0). |
@NegativeOrZero |
Validates that the annotated element’s value is a non-positive number (less than or equal to 0). |
@Pattern(regexp) |
Validates that the annotated element’s value matches the specified regular expression. |
@Digits(integer=, fraction=) |
Validates that the annotated element’s value has the specified number of integer and fractional digits. |
@AssertTrue |
Validates that the annotated element’s value is true. |
@AssertFalse |
Validates that the annotated element’s value is false. |
@Past |
Validates that the annotated element’s value is a date in the past. |
@PastOrPresent |
Validates that the annotated element’s value is a date in the past or present. |
@Future |
Validates that the annotated element’s value is a date in the future. |
@FutureOrPresent |
Validates that the annotated element’s value is a date in the present or future. |
Example Usage
Here’s an example of how you can use these annotations in a model class:
1 | import javax.validation.constraints.*; |
In a Spring MVC controller, you can use the @Valid
annotation to trigger validation and handle the results with a BindingResult
object:
1 | import org.springframework.stereotype.Controller; |
By using these annotations and validation mechanisms, you can ensure that your application’s data meets the necessary constraints and handle invalid input gracefully.