Custom data validation annotations in Spring Boot

Custom data validation annotations in Spring Boot

In Spring Boot, we can use the JSR-303 data validation specification to verify the validity of form data. JSR-303 provides some common data validation annotations, such as @NotNull, @NotBlank, @Sizeand so on. However, in actual development, we may need to customize data validation annotations to meet specific needs. This article will introduce how to customize data validation annotations in Spring Boot, and provide sample code to demonstrate its usage.

insert image description here

Custom validation annotations

In Spring Boot, we can customize data validation annotations by defining annotations and using @Constraintannotations . The following is a custom annotation @ZipCodeto check whether the zip code is legal:

@Target({
    
    ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ZipCodeValidator.class)
public @interface ZipCode {
    
    

    String message() default "Invalid zip code";

    Class<?>[] groups() default {
    
    };

    Class<? extends Payload>[] payload() default {
    
    };

    @Target({
    
    ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    @interface List {
    
    
        ZipCode[] value();
    }
}

In the above code, we use @Constraintthe annotation to indicate that the annotation needs to ZipCodeValidatorbe validated using the class. @ConstraintThe meaning of the parameters in the annotation is as follows:

  • validatedBy: Indicates which class to use for validation.
  • message: The message returned when the verification fails.
  • groups: check group.
  • payload: Verify load.

In annotations, we define an ZipCodeValidator.Listinternal annotation to support @ZipCodethe use of multiple annotations.

custom validator

After customizing the validation annotation, we also need to implement the validator. Here is an example code for a ZipCodeValidatorvalidator :

public class ZipCodeValidator implements ConstraintValidator<ZipCode, String> {
    
    

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
    
    
        if (value == null) {
    
    
            return true;
        }
        Pattern pattern = Pattern.compile("\\d{5}");
        Matcher matcher = pattern.matcher(value);
        return matcher.matches();
    }
}

In the above code, we have implemented ConstraintValidator<ZipCode, String>the interface and overridden isValidthe method. isValidmethod is used for the actual validation logic. In this example, we use a regular expression to validate that the zip code conforms to the 5-digit format.

Use custom validation annotations

After defining custom validation annotations and validators, we can use custom validation annotations in Java objects. Here is a sample code:

public class Address {
    
    

    @ZipCode
    private String zipCode;

    // 省略 getter 和 setter 方法
}

In the code above, Addresswe zipCodehave used @ZipCodethe annotation of the class. When using, we don't need to specify messagethe parameter , because the parameter has been @ZipCodespecified in the annotation.

In controllers, we can use @Validannotations to indicate objects that need to be validated. For example:

@RestController
@RequestMapping("/addresses")
public class AddressController {
    
    

    @PostMapping
    public ResponseEntity<?> createAddress(@Valid @RequestBody Address address) {
    
    
        // 创建地址
        return ResponseEntity.ok().build();
    }
}

In the sample code above, we used @Validannotations to indicate that the objectRequestBody in the needs to be validated. AddressIf the validation fails, Spring Boot will automatically return a response with an error message.

Summarize

In this article, we introduced the method of customizing data validation annotations in Spring Boot, and provided sample code to demonstrate its usage. Using custom validation annotations can help us meet specific data validation requirements, thereby improving the security and reliability of web applications. If you need to perform data validation when developing web applications, and the default data validation annotations cannot meet your needs, please be sure to consider the method of using custom validation annotations.

Guess you like

Origin blog.csdn.net/2302_77835532/article/details/131326452