ID number, format verification: @IdCard (Validation + Hutool)

Target

Customize an annotation for verifying the 身份证号码 format@IdCard, which can be verified with the existing Validation parameters Compatible with the verification mechanism, the usage method is consistent with other verification annotations (use @Valid to annotate interface parameters).

Insert image description here

Verification logic

valid format

In line with national standards.

The citizen identity number is compiled in accordance with the national standard GB11643-1999 "Citizen Identity Number" and consists of 18 digits: the first 6 digits are the administrative division code, the 7th to 14th digits are the date of birth code, the 15th to 17th digits are the sequence code, and the 15th to 17th digits are the sequence code. The 18 bits are the check code.

Do not verify non-empty

ID card number annotation, the verification is格式; it does not verify whether it is empty (null or empty string). If the ID number is empty, this annotation verification can pass;

是否校验非空 should be determined based on 业务逻辑; if the business logic needs to verify that it is not empty, use the annotation @NotEmpty.

Tool for format verification: Hutool

Use the ID card format verification method provided by Hutool.

Note that Hutool verifies the ID card format and ignores X的大小写; that is, the uppercase and lowercase X is considered to express 罗马数字十.

rely

  1. Validation
  2. Hutool

Validation:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

Hutool:

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.22</version>
        </dependency>

core code

The content that needs to be customized includes two parts:

  1. annotation@IdCard
  2. validatorIdCardValidator

Annotation: @IdCard

package com.example.core.validation.idcard;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 身份证号码。字符串必须是格式正确的身份证号码。
 * <p>
 * {@code null} 或 空字符串,是有效的(能够通过校验)。
 * <p>
 * 支持的类型:字符串
 *
 * @author songguanxun
 * @since 1.0
 */
@Target({
    
    FIELD})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = IdCardValidator.class)
public @interface IdCard {
    
    

    /**
     * @return the error message template
     */
    String message() default "身份证号码,格式错误";

    /**
     * @return the groups the constraint belongs to
     */
    Class<?>[] groups() default {
    
    };

    /**
     * @return the payload associated to the constraint
     */
    Class<? extends Payload>[] payload() default {
    
    };

}

Validator: IdCardValidator

package com.example.core.validation.idcard;

import cn.hutool.core.util.IdcardUtil;
import com.example.core.validation.ResetMessageUtil;
import org.springframework.util.ObjectUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 身份证号码,格式校验器
 */
public class IdCardValidator implements ConstraintValidator<IdCard, String> {
    
    

    @Override
    public void initialize(IdCard constraintAnnotation) {
    
    
        ConstraintValidator.super.initialize(constraintAnnotation);
    }


    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
    
    
        if (ObjectUtils.isEmpty(value)) {
    
    
            return true;
        }

        if (value.contains(" ")) {
    
    
            ResetMessageUtil.reset(context, "身份证号码,格式错误:不能包含空格");
            return false;
        }

        return IdcardUtil.isValidCard(value);
    }

}

use

@IdCard is placed on the 身份证号码 field that needs to be formatted.

package com.example.web.response.model.param;

import com.example.core.validation.idcard.IdCard;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

@Data
@Schema(name = "新增用户Param")
public class UserAddParam {
    
    
    
    // 其他字段

    @IdCard
    @Schema(description = "身份证号码", example = "110101202301024130")
    private String idCard;

}

Supplementary code

ResetMessageUtil: Reset prompt information tool class

package com.example.core.validation;

import javax.validation.ConstraintValidatorContext;

/**
 * 参数校验 - 重置提示信息工具类
 */
public class ResetMessageUtil {
    
    

    /**
     * 重置提示信息
     */
    public static void reset(ConstraintValidatorContext context, String message) {
    
    
        context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
    }

}


Verification effect

Verification tool class (Hutool), test

Test the ID card verification method provided by Hutool.

package com.example;

import cn.hutool.core.util.IdcardUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

/**
 * 身份证号码校验测试(使用Hutool)
 */
@Slf4j
public class IdCardHutoolTest {
    
    

    @Test
    void test() {
    
    
        test("110101202301024130");
        test("11010120230102857X");
        test("11010120230102857x");
        test("110101202301024130啊啊啊啊");
    }


    private void test(String idCard) {
    
    
        boolean validCard = IdcardUtil.isValidCard(idCard);
        log.info("是否为身份证号码格式:{} = {}", idCard, validCard);
    }

}

Ability to correctly verify ID card format.
Insert image description here

Interface testing

The verification result is successful

Insert image description here
Insert image description here

Insert image description here

The verification result is failed

Insert image description here

Insert image description here

Guess you like

Origin blog.csdn.net/sgx1825192/article/details/134054603