| New file |
| | |
| | | package com.ruoyi.web.controller.tool; |
| | | |
| | | import java.util.regex.Matcher; |
| | | import java.util.regex.Pattern; |
| | | |
| | | public class IDCardValidatorWithEmpty { |
| | | // 定义支持空字符串的身份证号校验的正则表达式 |
| | | private static final String ID_CARD_REGEX = "^$|(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)"; |
| | | private static final String PHONE_REGEX = "^$|^1[3-9]\\d{9}$"; |
| | | private static final Pattern ID_CARD_PATTERN = Pattern.compile(ID_CARD_REGEX); |
| | | private static final Pattern PHONE_PATTERN = Pattern.compile(PHONE_REGEX); |
| | | |
| | | /** |
| | | * 校验身份证号的方法,允许空字符串 |
| | | * @param idCard 待校验的身份证号 |
| | | * @return 如果身份证号格式正确或者为空字符串返回 true,否则返回 false |
| | | */ |
| | | public static boolean isValidIDCard(String idCard) { |
| | | Matcher matcher = ID_CARD_PATTERN.matcher(idCard); |
| | | return matcher.matches(); |
| | | } |
| | | public static boolean isValidPhone(String phone) { |
| | | Matcher matcher = PHONE_PATTERN.matcher(phone); |
| | | return matcher.matches(); |
| | | } |
| | | |
| | | public static void main(String[] args) { |
| | | // 测试用的 15 位身份证号 |
| | | String idCard15 = "110105880620517"; |
| | | // 测试用的 18 位身份证号 |
| | | String idCard18 = "51370119990231853X"; |
| | | // 无效的身份证号 |
| | | String invalidIdCard = "123456789012345678"; |
| | | // 空字符串 |
| | | String emptyIdCard = ""; |
| | | String phone = "11212312312"; |
| | | |
| | | // 调用校验方法并输出结果 |
| | | System.out.println(idCard15 + " 是否为有效的身份证号: " + isValidIDCard(idCard15)); |
| | | System.out.println(idCard18 + " 是否为有效的身份证号: " + isValidIDCard(idCard18)); |
| | | System.out.println(invalidIdCard + " 是否为有效的身份证号: " + isValidIDCard(invalidIdCard)); |
| | | System.out.println("空字符串是否允许: " + isValidIDCard(emptyIdCard)); |
| | | System.out.println(phone + "是否为有效的手机号: " + isValidPhone(phone)); |
| | | } |
| | | } |