Implementation of Hibernate Validation Custom Annotation Verification

  • 2021-07-18 07:59:42
  • OfStack

Scenario: Attributes of String type, such as description, need to be validated. The validation rule is not to perform regular verification when description is empty, and regular verification when description is not empty. The above requirements Hibernate Validation have no annotations available for the above requirements, so customize one annotation and customize verification rules.

To customize comments to validate

Write a verification annotation, specify the validator class in the annotation, and the verification annotation corresponds to the validator 1 and 11. Write 1 validator class and write validator logic in the validator class. The validator must implement ConstraintValidator < ?, ? > Interface, the first parameter is the corresponding annotation, and the second parameter is the type of attribute to be verified

Code Sample

Verification annotation


package com.kunlun.validation.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

import com.kunlun.validation.validator.KlPatternValidator;

/**
 *  Custom validation comments 
 *  Rules: 
 * 1. If the string is an empty string or is null The regular check is not performed 
 * 2. If the string is not an empty string, regular verification must be performed 
 * @author xc
 * @date 2018 Year 1 Month 19 Sunday morning 11:38:02
 */
@Documented
//  Specify where this annotation can be used 
@Target(value= {ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
//  Specifies the validator that actually performs the validation, which is written by itself and must implement the ConstraintValidator Interface 
@Constraint(validatedBy=KlPatternValidator.class)
public @interface KlPattern {
  /*
   *  The comments for validation are as follows 3 A method must be, this is Hibernate Validation Required by the framework, otherwise the program will report an error when it is called again 
   * default Used to give a default value to a property 
   *  If no default value is given, you must specify a property value for the property when using annotations, otherwise an error will be reported 
   *  Given a default value, you can use annotations without specifying property values 
   */
  String message() default " Not in line with the rules! ";

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

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

  //  Not added default Given the default value, this attribute must be assigned when using annotations, otherwise an error will be reported 
  String regex();
  // value Attribute, plus the default "mercy"  So that this attribute can be used when annotations are not entered and errors will not be reported 
  String value() default "mercy";
}

Validator class corresponding to the above validation annotation


package com.kunlun.validation.validator;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.kunlun.validation.annotation.KlPattern;

/**
 * KlPatternValidator Yes KlPattern Annotate the validator actually called 
 *  In KlPatternValidator Complete verification logic in 
 * 
 * @author xc
 * @date 2018 Year 1 Month 19 Sunday morning 11:44:38
 */
public class KlPatternValidator implements ConstraintValidator<KlPattern, String> {

  private String regex;

  /**
   *  Pass initialize() You can get the attribute value in the annotation 
   */
  @Override
  public void initialize(KlPattern constraintAnnotation) {
    ConstraintValidator.super.initialize(constraintAnnotation);
    regex = constraintAnnotation.regex();
  }

  /**
   *  Actual verification logic 
   *  The return value is true Indicates that the verification is passed, 
   *  The return value is false Indicates that the authentication failed 
   */
  @Override
  public boolean isValid(String s, ConstraintValidatorContext ctx) {

    //  If the request parameter transmitted from the current front end is an empty string, or if it is not transmitted, no subsequent regular verification will be performed 
    if ("".equals(s) || s == null) {
      return true;
    }

    //  Perform regular check 
    if(s.matches(regex)) {
      return true;
    }

    return false;
  }
}

Related articles: