在我们日常工作中,会有这样的需求,假如前端新增、修改数据时,后端要针对身份证号格式进行校验 ,但是框架有没有提供现成的关于身份证号校验的注解,如果写在业务层里,无异于会增加代码的复杂度,综上考虑,使用自定义注解是比较方便且高效的
注解代码:
@Documented @Constraint(validatedBy = IdCardValidator.class) @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface IdCard { String message() default "身份证号格式不正确"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
手机号校验业务处理:
public class IdCardValidator implements ConstraintValidator<IdCard, String> { private static final Pattern PATTERN = Pattern.compile("^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\\d{3}([0-9