定义一个注解@Ident 实现注解方法IdentValidated
/** * 身份证号码验证 */ @Constraint(validatedBy = { IdentValidated.class }) @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD}) public @interface Ident { String message() default "请输入有效身份证号码"; Class<?>[] groups() default { }; Class<? extends Payload>[] payload() default { }; /** * Defines several {@code @NotBlank} constraints on the same element. * * @see NotBlank */ @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE }) @Retention(RUNTIME) @Documented public @interface List { NotBlank[] value(); } }实现注解方法
@Slf4j public class IdentValidated implements ConstraintValidator<Ident,String> { Map<String,String> map=new HashMap<String,String>(){{ put("11","北京"); put("12","天津"); put("13","河北"); put("14","山西"); put("15","内蒙古"); put("21","辽宁"); put("22","吉林"); put("23","黑龙江"); put("31","上海"); put("32","江苏"); put("33","浙江"); put("34","安徽"); put("35","福建"); put("36","江西"); put("37","山东"); put("41","河南"); put("42","湖北"); put("43","湖南"); put("44","广东"); put("45","广西"); put("46","海南"); put("50","重庆"); put("51","四川"); put("52","贵州"); put("53","云南"); put("54","西藏"); put("61","陕西"); put("62","甘肃"); put("63","青海"); put("64","宁夏"); put("65","新疆"); put("71","台湾"); put("81","香港"); put("82","澳门"); }}; @Override public void initialize(Ident constraintAnnotation) { } @Override public boolean isValid(String value, ConstraintValidatorContext context) { log.info("value:{}",value); if(StringUtils.isEmpty(value)){ return false; } /** * 身份证格式不正确 * 身份证号码正则检查 * 检查不通过直接返回false */ if(!value.matches(Validation.IDEN_NO_REG)) { return false; } /** * 身份证前两位校验 */ String s = value.substring(0, 2); String s1 = map.get(s); if(s1==null){ return false; } /** * 出生日期校验 */ /*String bearth="/^(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)$/"; if(!value.substring(6,14).matches(bearth)) { return false; }*/ return identValid(value); } /** * 根据身份证主体码(前17位)分别与对应的加权因子(表1)计算乘积再求和,根据所得结果与11取模得到X值。 * 根据 X 值查询表2,得出a18即校验码值 * @param val * @return */ private Boolean identValid(String val) { // String sid="/^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$/"; Integer[] factor = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }; String[] parity = {"1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"}; String code = val.substring(0, 17); String[] split = code.split(""); Integer sum = 0; for (int i = 0; i < split.length; i++) { sum+=Integer.parseInt(split[i])*factor[i]; } return val.endsWith(parity[sum % 11]); } }具体使用参照@Validated 注解用法 注意 使用对象嵌套形式需要使用 @Valid加在父级属性上