SpringBoot verification framework: Yue Library

validator

<p>Lightweight server verification framework < / P > < p > supports annotation, complete functions and easy to use</p>

1, Function introduction

It mainly provides convenient background data verification function, supports single field or parameter verification, and also supports object verification through annotation, which is simple to use< Br > it provides basic non empty, length, size and other verification methods, as well as some special verification methods such as regular verification, ID card, telephone, email, IP and so on.

2, Annotation introduction

@Valid annotated element is a POJO object, which is used to check whether the values of all annotated fields of this object meet the expectations

Built in constraint in Bean Validation

annotation effect
@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 white space 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 maximum value of the annotation element must be less than or equal to a number
@Min The annotated element must be a number and its value must be greater than or equal to the specified minimum value
@DecimalMax The annotated element must be a number and its value must be less than or equal to the specified maximum value
@DecimalMin The annotated element must be a number and its value must be greater than or equal to the specified minimum value
@Digits The annotated element must be a number and its value must be within an acceptable range
@Positive Annotated elements must be strictly positive
@PositiveOrZero The annotated element must be a positive number 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 moment, date or time in the future.
@FutureOrPresent The annotated element must be a current or future moment, date or time.
@Size The size of the annotated element must be within the specified range
@Email The annotated element must be an email address
@Pattern The annotated element must conform to the specified regular expression

constraint attached to Hibernate Validator

annotation effect
@Length The size of the annotated string must be within the specified range
@Range The annotated element must be within the appropriate range
@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 length of the code point containing the character sequence is between min and max
@ConstraintComposition Boolean operator that applies to all constraints of the combined constraint annotation
@SafeHtml Verify the rich text value provided by the user to ensure that it does not contain malicious code, such as embedded < script > elements
@UniqueElements Verify that each object in the provided collection is unique, that is, two equal elements cannot be found in the collection
@EAN Check whether the annotated character sequence is a valid EAN 13 number. Verify the length of the number and check the number
@ISBN Check whether the annotated character sequence is a valid ISBN. The length of the number and the check number are verified
@LuhnCheck Luhn algorithm checking constraints
@Mod10Check Modulo 10 check constraints
@Mod11Check Modulo 11 check 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

constraint attached to Yue Validator

annotation effect
@Cellphone Mobile phone number verification
@IdCard ID card verification
@PlateNumber China license plate number verification
@Birthday Birthday verification
@Chinese Chinese verification
@English English verification
@UUID UUID verification
@IPV4 IPV4 address verification
@IPV6 IPV6 address verification
@MacAddress MAC address verification

3, Parameter verification

Single parameter verification

Single parameter verification

// parameter
String name = validationIPO.getName();
String email = validationIPO.getEmail();
String cellphone = validationIPO.getCellphone();
int age = validationIPO.getAge();
DateTime birthday = validationIPO.getBirthday();

// Get parameter validator Bean injection
import ai.yue.library.base.validation.Validator;
@Autowired
private Validator validator;

// Get parameter validator - static method
Validator.getValidatorAndSetParam(email).email("email");

// Single parameter verification
validator.param(email).email("email");
validator.param(cellphone).cellphone("cellphone");
validator.param(name).notNull("name").chinese("name").length(1, 30, "name");

Single parameter verification - concatenate through param() (switch the verification object directly)

validator.param(name).notNull("name").param(email).length(5, 25, "email").param(age).min(20, "age").max(60, "age");

POJO object verification (< font color = Red > recommended < / font >)

Define annotations on the properties of the class, and support custom error messages

@Data
public class ValidationIPO {

    @NotEmpty(message = "Name cannot be empty")
    @Length(max = 20, message = "The name cannot exceed 20 words")
    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;
    
    @Pattern(regexp = "[1-9]([0-9]{5,11})")
    private String qq;
    
}

Method 1: Controller layer, verify < font color = Red > (recommended) < / font > through annotation @ Valid

@PostMapping("/valid")
public Result<?> valid(@Valid ValidationIPO validationIPO) {

**Method 2: * * by calling validator Valid() method

validator.valid(validationIPO);
// Hyphenation is also supported
validator.valid(validationIPO).param(birthday).birthday("birthday");

**Method 3: * * add @ Valid annotation to POJO class

@Data
@Valid
public class ValidationIPO {
	// ...
}

And receive the entity parameters at the Controller layer

@PostMapping("/valid")
public Result<?> valid(ValidationIPO validationIPO) {

Process when the verification fails

If the verification fails, ValidateException (runtime exception) will be thrown, and the ResultExceptionHandler class has been handled by default.

Example of error response:

{
    "code": 433,
    "msg": "Parameter verification failed, please refer to API Check and try again",
    "flag": false,
    "count": null,
    "data": [
        {
            "errorkey": "cellphone",
            "errorValue": null,
            "errorHintMsg": "Not a legal mobile number"
        },
        {
            "errorkey": "idcard",
            "errorValue": "500223199607125633",
            "errorHintMsg": "Not a legal ID number."
        }
    ]
}

Added by mailtome on Fri, 04 Mar 2022 04:16:19 +0200