spring-boot-starter-validation
is a module used in Spring Boot to support data validation. It is built on the Java Validation API (JSR-380) and provides a convenient way to validate data in applications. Here is the basic way to use spring-boot-starter-validation
:
Quick Start
1. Add dependencies:
In your Spring Boot project’s pom.xml
file, add the following dependencies:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
If you use Gradle, you can add this to your build.gradle
file:
implementation 'org.springframework.boot:spring-boot-starter-validation'
2. Create validation rules:
In classes that require data validation, mark fields using annotations in the Java Validation API to define validation rules. For example, use @NotBlank
to ensure a field is not blank:
public class MyRequest {<!-- --> @NotBlank private String name; /** * 1.@NotNull: cannot be null, but can be empty(""," "," ") * 2.@NotEmpty: cannot be null, and the length must be greater than 0 (" "," ") * 3.@NotBlank: It can only be used on String, it cannot be null, and after calling trim(), the length must be greater than 0 ("test"), that is, there must be actual characters. * Copy code */ @NotBlank(message="Username cannot be blank") private String userName; @NotBlank(message="Age cannot be blank") @Pattern(regexp="^[0-9]{1,2}$",message="Incorrect age") private String age; @AssertFalse(message = "Must be false") private Boolean isFalse; /** * If it is empty, it will not be checked. If it is not empty, it will be checked. */ @Pattern(regexp="^\d{4}(-)(1[0-2]|0?\d)\1([0-2]\ d|\d|30|31)$",message="The date of birth format is incorrect") private String birthday; @Pattern(regexp = "^[M|F|U|m|f|u]{1}$") private String gender; @Pattern(regexp = "^(MS)?(MR)?(PRO)?(MRS)?(DOC)?$") private String civility; @Size(min = 1, message = "field names can't be empty") private List<String> names = new ArrayList(); // Other fields and methods... }
This is just a simple example, the Java Validation API provides many other annotations, such as @NotNull
, @Min
, @Max
, @Email
etc. to meet various verification needs.
3. Use validation in the controller:
Where input data needs to be validated, typically in a Spring MVC controller, use the @Valid
annotation to enable validation:
@RestController public class MyController {<!-- --> @PostMapping("/submit") public ResponseEntity<String> submit(@Valid @RequestBody MyRequest request) {<!-- --> // Process the validated request return ResponseEntity.ok("Request is valid"); } }
In the above example, the @Valid
annotation is used to tell Spring Boot to validate the MyRequest
object. If validation fails, a MethodArgumentNotValidException
exception will be thrown.
4. Handling verification errors:
To handle validation errors, you can use a BindingResult
object. Modify the controller method to accept the BindingResult
parameter and check for errors:
@RestController public class MyController {<!-- --> @PostMapping("/submit") public ResponseEntity<String> submit(@Valid @RequestBody MyRequest request, BindingResult bindingResult) {<!-- --> if (bindingResult.hasErrors()) {<!-- --> // Handle validation errors return ResponseEntity.badRequest().body("Validation errors"); } // Process the validated request return ResponseEntity.ok("Request is valid"); } }
These are the basic steps for using spring-boot-starter-validation
. In this way, you can easily perform data validation in Spring Boot applications to ensure the validity of the input data.
Group verification
When using Spring Boot Validation for group verification, you can use the @GroupSequence
annotation provided by the Validation API to define the verification sequence. Below is a simple example that demonstrates how to implement group validation in Spring Boot.
First, assume you have a Java Bean class that contains grouping information:
import javax.validation.GroupSequence; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; public class MyRequest {<!-- --> //Define grouping public interface FirstGroup {<!-- -->} public interface SecondGroup {<!-- -->} // Define the grouping order @GroupSequence({<!-- -->FirstGroup.class, SecondGroup.class}) public interface AllGroups {<!-- -->} // Group verification example @NotNull(message = "ID cannot be empty", groups = FirstGroup.class) private Long id; @NotBlank(message = "Name cannot be blank", groups = SecondGroup.class) private String name; @NotNull(groups = {<!-- -->FirstGroup.class, SecondGroup.class}, message = "Password cannot be empty") private String password; //Omit other fields and methods }
In the above example, we define two groups FirstGroup
and SecondGroup
, and then define their order using the @GroupSequence
annotation. Next, use the @NotNull
and @NotBlank
annotations on the field, and specify the group to which the verification belongs through the groups
attribute.
Next, in your controller or service, use the @Validated
annotation to specify which group to use for validation:
import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; @RestController @Validated public class MyController {<!-- --> @PostMapping("/submit") public String submit(@Validated(MyRequest.FirstGroup.class) @RequestBody MyRequest request) {<!-- --> // handle the request return "Request is valid"; } @PostMapping("/update") public String update(@Validated(MyRequest.SecondGroup.class) @RequestBody MyRequest request) {<!-- --> // handle the request return "Request is valid"; } }
In the above example, the @Validated
annotation is used to mark the controller, and then the @Validated
annotation is used on the method parameters to specify which grouping is used for validation. FirstGroup
is used for verification in the /submit
interface, and SecondGroup
is used for verification in the /update
interface. check.
In this way, you can implement group-based verification. Please note that the order of grouping is defined in the @GroupSequence
annotation.
The difference between @Validated and @Valid
@Validated: Provides a grouping function, which can use different verification mechanisms according to different groups when entering parameters for verification. There is also information on this website, so I won’t go into details.
@Valid: As a standard JSR-303 specification, there is no ability to absorb grouping yet.
Commonly used annotations
In Spring Boot, the common annotations used for data validation are the annotations from the Java Validation API (JSR-380). The following are some commonly used annotations:
- General annotations:
@NotNull
: Verify that the annotated element value is not null.@Null
: Verify that the annotated element value is null.@AssertTrue
: Verify that the annotated element value istrue
.@AssertFalse
: Verify that the annotated element value isfalse
.@Min(value)
: Verify that the annotated element value is greater than or equal to the specified value.@Max(value)
: Verifies that the annotated element value is less than or equal to the specified value.@Size(max, min)
: Verify that the size of the annotated element value is within the specified range.@Digits(integer, fraction)
: Verify that the integer part and fractional part of the annotation element value do not exceed the specified value.
- String validation:
@NotBlank
: Verify that the annotation element value is not empty (not null, the length is greater than 0 after removing the leading and trailing spaces).@NotEmpty
: Verify that the annotated element value is not null and not empty.@Email
: Verifies that the annotation element value is a valid email address.
- Numerical verification:
@Positive
: Verify that the annotated element value is a positive number.@PositiveOrZero
: Verify that the annotated element value is a non-negative number.@Negative
: Verify that the annotated element value is a negative number.@NegativeOrZero
: Verify that the annotated element value is a non-positive number.
- Date and time verification:
@Past
: Verify that the annotation element value is a date or time in the past.@PastOrPresent
: Verifies that the annotation element value is a past or current date or time.@Future
: Verify that the annotation element value is a future date or time.@FutureOrPresent
: Verifies that the annotated element value is a future or current date or time.
- Custom annotation:
- You can also create custom annotations to define your own validation logic by implementing the
ConstraintValidator
interface and declare it using the@Constraint
annotation.
These annotations can be used on Java Bean fields for data validation. In Spring Boot, usually used with @Valid
or @Validated
to trigger validation. In the examples mentioned above, the use of some common annotations has been demonstrated.
Example:
The following are commonly used definition verification annotations and examples of their use:
@NotNull
: The annotated element must not be null. For example:
public class User {<!-- --> @NotNull(message = "Name cannot be empty") private String name; // ...other fields... }
@NotEmpty
: The annotated object must not be empty (data: String, Collection, Map, arrays). For example:
public class User {<!-- --> @NotEmpty(message = "The role list cannot be empty") private List<Role> roles; // ...other fields... }
@NotBlank
: CharSequence subtype, verify that the annotation element value is not empty (including not null or the length is 0 after removing the first space). For example:
public class User {<!-- --> @NotBlank(message = "Mobile phone number cannot be blank") private String phoneNumber; // ...other fields... }
@Min
: Verifies whether the number is less than or equal to the specified minimum value. For example:
public class User {<!-- --> @Min(value = 18, message = "Age cannot be less than 18 years old") private int age; // ...other fields... }
@Max
: Verifies whether the number is greater than or equal to the specified maximum value. For example:
public class User {<!-- --> @Max(value = 60, message = "Age cannot exceed 60 years old") private int age; // ...other fields... }
@Pattern
: Used to verify whether a string conforms to the specified regular expression. For example:
public class User {<!-- --> @Pattern(regexp = "^\d{6}$", message = "The format of the ID number is incorrect") private String idCardNumber; // ...other fields... }
@Size
: used to limit the length of character sequences (such as String, Collection, Map, etc.), supporting min and max attributes. For example:
public class User {<!-- --> @Size(min = 6, max = 18, message = "Password length must be between 6-18") private String password; // ...other fields... }
@Email
: used to verify email addresses. For example:
public class User {<!-- --> @Email(message = "Please enter the correct email address") private String email; // ...other fields... }
@Past
: Used to determine whether the date is in the past. For example:
public class User {<!-- --> @Past(message = "Birthday cannot be later than now") private Date birthday; // ...other fields... }
@Future
: Used to determine whether the date is in the future. For example:
public class User {<!-- --> @Future(message = "Deadline must be in the future") private Date deadline; // ...other fields... }
@DecimalMax
: Verifies whether the number is less than or equal to the specified maximum value. For example:
public class User {<!-- --> @DecimalMax(value = "100.00", message = "Amount cannot exceed 100 yuan") private double amount; // ...other fields... }
@DecimalMin
: Verifies whether the number is greater than or equal to the specified minimum value. For example:
public class User {<!-- --> @DecimalMin(value = "1.00", message = "The price cannot be less than 1 yuan") private double price; // ...other fields... }
The above are common data verification annotations. Using these annotations can make our applications more robust and avoid illegal data input.