輸入字符串格式:手機號,座機,手機號...,逗號分隔,需逐個驗證格式正確性。
function validatePhones(input) {
if (!input || !input.trim()) return { valid: false, error: '輸入為空' };
const phones = input.split(',').map(s => s.trim()).filter(s => s);
const results = [];
const mobileRe = /^1[3-9]\d{9}$/; // 簡化版,實際可更嚴格
const landlineRe = /^0\d{2,3}-?\d{7,8}(-\d{3,4})?$/;
for (const phone of phones) {
const isMobile = mobileRe.test(phone);
const isLandline = landlineRe.test(phone);
results.push({
phone,
valid: isMobile || isLandline,
type: isMobile ? 'mobile' : (isLandline ? 'landline' : 'invalid')
});
}
const allValid = results.every(r => r.valid);
return { valid: allValid, details: results };
}
// 使用
const r = validatePhones("13800138000,010-12345678,13900139000");
console.log(r.valid, r.details);
// 匹配整個字符串:每個子項必須是手機或座機,逗號分隔
const fullRe = /^(?:(?:1[3-9]\d{9})|(?:0\d{2,3}-?\d{7,8}(-\d{3,4})?))(?:,(?:(?:1[3-9]\d{9})|(?:0\d{2,3}-?\d{7,8}(-\d{3,4})?)))*$/;
function validatePhonesSingleRegex(input) {
return fullRe.test(input);
}
| 片段 | 含義 |
|---|---|
1[3-9]\d{9} | 手機號:1 開頭,第二位 3-9,共 11 位 |
0\d{2,3} | 座機區號:0 開頭,2-3 位數字 |
-? | 可選連字符 |
\d{7,8} | 本地號碼 7-8 位 |
(-\d{3,4})? | 可選分機號 |
(?:...) | 非捕獲分組,僅分組不捕獲 |
*$ | 重複 0 次或多次,直到字符串結尾 |
libphonenumber-js 庫,支援國際號碼、運營商識別、格式化