实现身份证号码的校验
类似:https://blog.csdn.net/winerpro/article/details/120387631
校验注解
@Target({ElementType.FIELD,ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {IdCardNoCheckValidator.class})
public @interface IdCardNoCheck {
String message() default "身份证号码格式错误";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default { };
}
校验类
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Calendar;
/**
* @author yangwenxin
* @Date 2022/2/23
* @Description
*/
public class IdCardNoCheckValidator implements ConstraintValidator<IdCardNoCheck,String> {
private IdCardNoCheck idCardNoCheck;
@Override
public void initialize(IdCardNoCheck constraintAnnotation) {
this.idCardNoCheck = idCardNoCheck;
}
@Override
public boolean isValid(String str, ConstraintValidatorContext constraintValidatorContext) {
if (str == null){
return false;
}
str = str.toUpperCase();
if (str.length() != 15 && str.length() != 18) {
return false;
}
int y = 0, m = 0, d = 0;
if (str.length() == 15) {
y = Integer.parseInt("19" + str.substring(6, 8), 10);
m = Integer.parseInt(str.substring(8, 10), 10);
d = Integer.parseInt(str.substring(10, 12), 10);
} else if (str.length() == 18) {
if (str.indexOf("X") >= 0 && str.indexOf("X") != 17) {
return false;
}
char verifyBit = 0;
int sum = (str.charAt(0) - '0') * 7 + (str.charAt(1) - '0') * 9 + (str.charAt(2) - '0') * 10
+ (str.charAt(3) - '0') * 5 + (str.charAt(4) - '0') * 8 + (str.charAt(5) - '0') * 4
+ (str.charAt(6) - '0') * 2 + (str.charAt(7) - '0') * 1 + (str.charAt(8) - '0') * 6
+ (str.charAt(9) - '0') * 3 + (str.charAt(10) - '0') * 7 + (str.charAt(11) - '0') * 9
+ (str.charAt(12) - '0') * 10 + (str.charAt(13) - '0') * 5 + (str.charAt(14) - '0') * 8
+ (str.charAt(15) - '0') * 4 + (str.charAt(16) - '0') * 2;
sum = sum % 11;
switch (sum) {
case 0:
verifyBit = '1';
break;
case 1:
verifyBit = '0';
break;
case 2:
verifyBit = 'X';
break;
case 3:
verifyBit = '9';
break;
case 4:
verifyBit = '8';
break;
case 5:
verifyBit = '7';
break;
case 6:
verifyBit = '6';
break;
case 7:
verifyBit = '5';
break;
case 8:
verifyBit = '4';
break;
case 9:
verifyBit = '3';
break;
case 10:
verifyBit = '2';
break;
default:
break;
}
if (str.charAt(17) != verifyBit) {
return false;
}
y = Integer.parseInt(str.substring(6, 10), 10);
m = Integer.parseInt(str.substring(10, 12), 10);
d = Integer.parseInt(str.substring(12, 14), 10);
}
int currentY = Calendar.getInstance().get(Calendar.YEAR);
/*
* if(isGecko){ currentY += 1900; }
*/
if (y > currentY || y < 1870) {
return false;
}
if (m < 1 || m > 12) {
return false;
}
if (d < 1 || d > 31) {
return false;
}
return true;
}
}
使用:在需要校验的属性上面加上@IdCardCheck