validator
- Excellent server validation framework
validator
, fully functional, easy to use - Perfect check mode, support single parameter write check, POJO object check, grouping check
- Rich verification annotations, more appropriate domestic verification scenarios
- Friendly exception prompt, error quickly locate, development is easy to understand
I. Function introduction
Provides convenient background data verification function, supports single field or parameter verification, also supports object verification by annotations, simple usage. Provides the basic non-null, length, size and other verification methods, also provides some special regular verification, ID card, phone, email, IP and other verification methods.
Second, notes and introduction
The @validated element is a POJO object that checks whether the values of all the annotated fields on this object conform to expectations
The constraint is built into the Bean Validation
annotations | role |
---|---|
@Null | The annotated element must be NULL |
@NotNull | The annotated element must not be NULL |
@NotBlank | The annotated element must not be empty and must contain at least one non-whitespace character |
@NotEmpty | The annotated element must be non-empty |
@AssertTrue | The annotated element must be true |
@AssertFalse | The annotated element must be false |
@Max | The annotated element must be a number whose value must be less than or equal to the specified maximum |
@Min | The annotated element must be a number whose value must be greater than or equal to the specified minimum |
@DecimalMax | The annotated element must be a number whose value must be less than or equal to the specified maximum |
@DecimalMin | The annotated element must be a number whose value must be greater than or equal to the specified minimum |
@Digits | The annotated element must be a number and its value must be within an acceptable range |
@Positive | The annotated element must be strictly positive |
@PositiveOrZero | The annotated element must be positive or 0 |
@Negative | The annotated element must be a strictly negative number |
@NegativeOrZero | The annotated element must be negative or 0 |
@Past | The annotated element must be a moment, date, or time in the past |
@PastOrPresent | The annotated element must be a moment, date, or time in the past or present |
@Future | The annotated element must be a future moment, date, or time. |
@FutureOrPresent | The annotated element must be a present or future moment, date, or time. |
@Size | The size of the annotated element must be within the specified range |
The annotated element must be an E-mail address | |
@Pattern | The annotated element must conform to the specified regular expression |
Hibernate Validator has additional constraints
annotations | role |
---|---|
@Length | The size of the annotated string must be within the specified range |
@Range | The annotated element must be in the appropriate scope |
@URL | Verify that the annotated string is a URL |
@Currency | The monetary amount must be in the correct monetary unit |
@CreditCardNumber | The annotated element must represent a valid credit card number |
@CodePointLength | Verify that the code point containing the character sequence is between min and Max in length |
@ConstraintComposition | Boolean operator that applies to all constraints of the composite constraint annotation |
@SafeHtml | Validate the user-supplied rich text value to ensure that it does not contain malicious code, such as embedded<script> The element |
@UniqueElements | Verify that every object in the supplied collection is unique, that is, two equal elements cannot be found in the collection |
@EAN | Check if the annotated character sequence is a valid EAN 13 number. The length of the verification number and the parity number |
@ISBN | Checks if the annotated character sequence is a valid ISBN. The length of the digit and the parity digit are validated |
@LuhnCheck | Luhn’s algorithm checks constraints |
@Mod10Check | Modulo 10 checks for constraints |
@Mod11Check | Modulo 11 checks for constraints |
@ParameterScriptAssert | Method-level constraints that evaluate script expressions based on annotated methods or constructors |
@ScriptAssert | Class-level constraints that evaluate script expressions based on annotated elements |
Yue Validator additional constraint
annotations | role |
---|---|
@Cellphone | Mobile phone number check |
@IdCard | Verification of identity card |
@PlateNumber | China license plate verification |
@Birthday | Birthday check |
@Chinese | Check in Chinese |
@English | English checking |
@UUID | UUID check |
@IPV4 | IPV4 Address Verification |
@IPV6 | IPV6 Address Verification |
@MacAddress | MAC Address Verification |
@CarDrivingLicence | Verify whether it is a driving license (only: Chinese driving license file number) |
@CarVin | Verify whether it is the frame number |
@CreditCode | Is a valid uniform social credit code |
@ZipCode | Verify whether it is a zip code (China) |
3. Parameter verification
Single parameter check
Check parameter definition: a single parameter
String name = validationIPO.getName();
String email = validationIPO.getEmail();
String cellphone = validationIPO.getCellphone();
int age = validationIPO.getAge();
DateTime birthday = validationIPO.getBirthday();
Copy the code
Get parameter validator: via Bean injection
@Autowired
private Validator validator;
Copy the code
Get parameter validator: by static method
Validator.getValidatorAndSetParam(email).email("email");
Copy the code
Single parameter check
validator.param(email).email("email");
validator.param(cellphone).cellphone("cellphone");
validator.param(name).notNull("name").chinese("name").length(1.30."name");
Copy the code
Single parameter verification: concatenation through param() (directly switch the verification object)
validator.param(name).notNull("name").param(email).length(5.25."email").param(age).min(20."age").max(60."age");
Copy the code
Verification of POJO objects (recommended)
Validation parameter definitions: POJO objects (defining annotations on class attributes and supporting custom error messages)
@Data
public class ValidationIPO {
@notempty (message = "name cannot be empty ")
@length (Max = 20, message = "name cannot exceed 20 characters ")
private String name;
private DateTime birthday;
@IdCard
private String idcard;
@Max(30)
@Min(12)
private int age;
@Email
@Length(max = 50)
private String email;
@Cellphone
private String cellphone;
@ the Pattern (regexp = "[1-9] ([0-9] {5, 11})")
private String qq;
}
Copy the code
Verification Mode 1: At the Controller layer, using the @ “Validated” comment (recommended)
@PostMapping("/valid")
publicResult<? > valid(@Validated ValidationIPO validationIPO) {
Copy the code
Verification method 2: Call validator.valid()
validator.valid(validationIPO);
// Also support conjunctions
validator.valid(validationIPO).param(birthday).birthday("birthday");
Copy the code
Verification mode 3:
- will
@Validated
Annotations are added to the POJO class
@Data
@Validated
public class ValidationIPO {
// ...
}
Copy the code
- in
Controller
Layer receives this entity parameter
@PostMapping("/valid")
publicResult<? > valid(ValidationIPO validationIPO) {Copy the code
Packet check
When the same POJO is added, deleted, modified, and checked, grouping verification is particularly important. For example, id is not allowed to be passed in when adding POJO, and ID must be present when modifying POJO. The usage is as follows:
Sample POJO (with a groups attribute) :
@Data
public class ValidationGroupIPO extends ValidationGroups {
@Null(groups = {Create.class})
@NotNull(groups = {Delete.class, Update.class, Read.class})
private Long id;
}
Copy the code
Verification mode: Specify the @Validated value attribute on the controller as follows:
@PostMapping("/validationGroupCreate")
publicResult<? > validationGroupCreate(@Validated(ValidationGroups.Create.class) ValidationGroupIPO validationGroupIPO) {
Copy the code
Group verification can be used flexibly and supports the following capabilities:
- use
GroupSequence
Annotation can specify the group check order, and also has short circuit capability - use
GroupSequenceProvider
Annotation can dynamically specify the grouping verification order to solve the pain point problem of multi-field combination logic verification, but it needs to be realized by itselfDefaultGroupSequenceProvider
interface
Reference 1, reference 2
Iv. Abnormal verification processing
When the verification fails, a ValidateException is thrown. By default, the Yue-Library intercepts the Exception in the ResultExceptionHandler class and converts the exception message into a friendly RESTful response.
The following is an example of an error response:
{
"code": 433."msg": "Parameter verification failed, please refer to API verification and try again"."flag": false."count": null."data": [{"errorkey": "cellphone"."errorValue": null."errorHintMsg": "Not a legitimate cell phone number."
},
{
"errorkey": "idcard"."errorValue": "500223199605156666"."errorHintMsg": "Not a legitimate ID number."}}]Copy the code
Fifth, expand knowledge
@Valid
Annotations are provided in Java, and validation does not support specifying checksum groups@Validated
Annotations are provided by the Spring extension and are recommended for specifying verification groups during validation- Validation also supports recursive validation (that is, poJOs within POJOs)
- For how to customize validation annotations, refer
@Cellphone
,@IdCard
Etc. (i.e., yue-Library extension implementation) to verify annotations