在項目開發中,經常需要對用戶輸入的郵箱、手機號、身份證、日期、URL 等格式進行校驗。下面提供一個封裝良好、開箱即用的 Validation 類,包含常用正則常量與靜態校驗方法,可直接集成到專案中。
public class Validation {
// 常用正則
public static final String EMAIL = "\\w+(\\.\\w+)*@\\w+(\\.\\w+)+";
public static final String PHONE = "(^(\\d{2,4}[-_-—]?)?\\d{3,8}([-_-—]?\\d{3,8})?([-_-—]?\\d{1,7})?$)|(^0?1[35]\\d{9}$)";
public static final String MOBILE = "^(13[0-9]|15[0-9]|18[0-9])\\d{8}$"; // 注意:現代號段需擴展
public static final String IDCARD = "((11|12|13|14|15|21|22|23|31|32|33|34|35|36|37|41|42|43|44|45|46|50|51|52|53|54|61|62|63|64|65)\\d{4})" +
"(([1|2]\\d{3}[0|1]\\d[0-3]\\d\\d{3}[Xx0-9])|([0-9]{2}[0|1]\\d[0-3]\\d\\d{3}))";
public static final String URL = "^(http|www|ftp)?(://)?(\\w+(-\\w+)*)(\\.(\\w+(-\\w+)*))*((:\\d+)?)?(/(\\w+(-\\w+)*))*(\\.?(\\w)*)?(\\?)?(((\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*(\\w*%)*(\\w*\\?)*(\\w*:)*(\\w*\\+)*(\\w*\\.)*(\\w*&)*(\\w*-)*(\\w*=)*)*(\\w*)*)$";
public static final String DATE_ALL = "..."; // 完整日期正則極長,建議改用 DateTimeFormatter 解析
public static final String STR_NUM = "^[0-9]+$";
public static final String STR_ENG = "^[A-Za-z]+$";
// ... 更多常量:INTEGER, DOUBLE, AGE, CODE, STR_SPECIAL 等
// 核心匹配邏輯
private static boolean Regular(String str, String pattern) {
if (str == null || str.trim().isEmpty()) return false;
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(str);
return m.matches();
}
// 公開靜態方法示例
public static boolean isEmail(String str) { return Regular(str, EMAIL); }
public static boolean isMobile(String str) { return Regular(str, MOBILE); }
public static boolean isPhone(String str) { return Regular(str, PHONE); }
public static boolean isIdCard(String str) {
if (StrisNull(str)) return false;
int len = str.trim().length();
if (len == 15 || len == 18) return Regular(str, IDCARD);
return false;
}
public static boolean isUrl(String str) { return Regular(str, URL); }
public static boolean isDate(String str) { return Regular(str, DATE_ALL); }
public static boolean isNumber(String str) { return Regular(str, DOUBLE); }
public static boolean isInteger(String str) { return Regular(str, INTEGER); }
// ... 其他 isXxx 方法
// 輔助方法
public static boolean StrisNull(String str) { return str == null || str.trim().isEmpty(); }
public static String nulltoStr(String str) { return StrisNull(str) ? "" : str; }
public static String filterStr(String str) { // 過濾特殊字符
Pattern p = Pattern.compile(STR_SPECIAL);
return p.matcher(str).replaceAll("").trim();
}
}
String email = "test@example.com";
String mobile = "13800138000";
if (Validation.isEmail(email)) {
System.out.println("郵箱格式正確");
}
if (Validation.isMobile(mobile)) {
System.out.println("手機號格式正確");
}
MOBILE 僅覆蓋 13/15/18 段,實際項目需根據最新號段(如 16, 17, 19 等)更新正則。LocalDate.parse() 或 DateTimeFormatter 進行解析校驗。Pattern.compile 較耗時,工具類中常量已預編譯為靜態,但每次調用仍會創建 Matcher,高頻場景可考慮緩存 Pattern 對象。