SoFunction
Updated on 2025-03-08

Detailed explanation of Java parameter verification: Use @Valid annotation and custom annotation to verify parameters

Many times we need to use a lot of logical judgments and verifications such as if, else, etc., so it will be very troublesome to perform some repeated parameter verification, and it will be difficult to maintain in the future.

And this way it can be usedValidationCommon verification operations include verification data type, format, length, range, uniqueness, etc.

Package: Packages are introduced in Java SE 6+ as part of the Bean Validation specification.This package provides a set of annotations and interfaces for easy data verification.

<!--        validationComponent dependencies-->
<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

For parameter verification statements generally written in business logic classes, they can be omitted. If@ValidFill in the annotation in the method parameters of the login interface:

@PostMapping("/login")
public RespBean login(@Valid @RequestBody User user) {
    ("{}", user);
    return (user);
}

@Valid annotation performs corresponding verification of the incoming parameters:

The annotation is used on the method parameters, and then the verification requirements for the parameter can be filled in the verification conditions in the entity class of the parameter.

/**
 * @author Z
 * @date 2023/9/27 21:25
 */
@Data
public class User {
    @NotNull //The account is not empty    //This @Mobile is a custom judgment annotation. The following is a detailed explanation of its creation.    @Mobile(required = true) 
    private String mobile;
​
    @NotNull //The password is not empty    @Length(min = 32)  //Length limit    private String password;
}

And for example: @Size(min=1, max=12) represents: the length is between 1 ~ 12 characters.For other judgment annotations, you can view them in the imported external library.

You can also determine the conditional annotationFor example, @Mobile's custom annotation:

1. Create a package:Validation

2. Create the required annotations:Mobile

3. For the writing method of this annotation, directly copy the annotation already written in the package, such as: @Notnull annotation to modify:(If there is an error, just delete it without using it)

@Notnull annotation is as follows:

@Target({, , ElementType.ANNOTATION_TYPE, , , ElementType.TYPE_USE})
@Retention()
@Repeatable()  //It's popular and deleted@Documented
@Constraint(validatedBy = {}) //Definition of verification rulespublic @interface NotNull {
    String message() default "{}";
    //Modify the verification message​
    Class<?>[] groups() default {};
​
    Class<? extends Payload>[] payload() default {};
​
}

And here is adding an attribute: (required)

 boolean required() default true;

Custom @Mobile is as follows:

/**
 * @author Z
 * @date 2023/9/28 8:53
 */
@Target({, , ElementType.ANNOTATION_TYPE, , , ElementType.TYPE_USE})
@Retention()
@Documented
//A class that defines your own verification rules: (Mobile phone number verification rules class)//Put the custom rule class into @Constraint(validatedBy={})@Constraint(validatedBy = {})
public @interface Mobile {
​
    boolean required() default true;
​
    //Information, the BindException is thrown. If the front-end page receives it, we need to catch the exception    String message() default "Mobile phone number format";
​
    Class<?>[] groups() default {};
​
    Class<? extends Payload>[] payload() default {};
}

We need to define the verification rules ourselves, create a verification rules class, and put it into @Constraint(validatedBy={})

Custom verification rules class:

/**
  * Mobile phone number verification rules
  *
  * @author Z
  * @date 2023/9/28 8:56
  */
public class MobileValidator implements ConstraintValidator<Mobile, String> {
​
    private boolean required = false;
​
    //Initialization: Getting whether it is required is required    @Override
    public void initialize(Mobile constraintAnnotation) {
        //Get the filled value: true or false        required = ();
    }
​
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        //Required: Use the mobile phone number verification tool to verify        if (required){
            return (value);
        //Not required:        }else {
            if ((value)){ //The number passed is empty                return true;
            }else {
                //The transmitted number is not empty, use the mobile phone number verification tool to verify                return (value);
            }
        }
    }
}

For mobile phone number verification tools:

Add dependencies:

<dependency>
    <groupId></groupId>
    <artifactId>commons-lang3</artifactId>
</dependency>

Use regular expressions to verify mobile phone numbers:

import .;
import ;
import ;
​
/**
  * Mobile phone number verification class (using regular expressions)
  *
  * @author Z
  * @date 2023/9/27 21:45
  */
public class ValidatorUtil {
​
    private static final Pattern mobile_pattern = ("[1]([3-9])[0-9]{9}$");
​
    public static boolean Mobile(String mobile) {
        if ((mobile)){
            return false;
        }
        Matcher matcher = mobile_pattern.matcher(mobile);
        return ();
    }
}

Summarize

This is the article about the detailed explanation of Java parameter verification using @Valid annotations and custom annotations for parameter verification. This is the end of this article. For more related Java @Valid annotations and custom annotations parameter verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!