Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Regular Expression Pattern to Check Phone Number
var patt = /^\(0\d{2}\)\d{6}$|^\(0\d{1}\)\d{7,8}$|(^0\d{1})-\d{7,8}$|(^0\d{2})-\d{6}$/
var phones = ['089-335482', '(089)335482', '02-23442798', '(02)23442798']; // correct phone numbers format
var length_errors = ['(089)35482', '(089)3354826', '(0889)335482', '(02)335482', '02-335482', '02-234427988']; // improper digits combination
var illegal_chars = ['(089)33548-', '(089-335482', '089=335482']; // contains illegal characters or missing essential characters
// Function to test pattern match
function validate_phone_number( phone ) {
var patt = /^\(0\d{2}\)\d{6}$|^\(0\d{1}\)\d{7,8}$|(^0\d{1})-\d{7,8}$|(^0\d{2})-\d{6}$/;
return phone.map( function(i) {
return patt.test( i );
});
}
// Usage
validate_phone_number( phones ); // return [true, true, true, true], all are valid phone numbers
validate_phone_number( length_errors ); // return [false, false, false, false, false, false], all are invalid phone numbers
validate_phone_number( illegal_chars ); // return [false, false, false]
@twlca

This comment has been minimized.

Copy link
Owner Author

twlca commented Feb 9, 2015

驗證輸入的電話或傳真號碼是否正確

可接受的電話號碼格式有:

   0xx-xxxxxx     // 例如 089-335482
   0x-xxxxxxx     // 例如 03-8227670
   0x-xxxxxxxx    // 例如 02-27371311
   (0xx)xxxxxx    // 例如 (089)335482
   (0x)xxxxxxx    // 例如 (03)8227670
   (0x)xxxxxxxx   // 例如 (02)27371311

也就是說區碼本身一定以 "0" 開頭,區碼祇能 2 個或 3 個數字;區碼以 "-" 與本地號碼相隔,或者是區碼界於括弧中,而直接接本地號碼;本地號碼在區碼為 3位數字時,一定為 6 位數字,中間不得有任何其他符號(包含空白或 "-");而本地號碼在區碼為 2 位數字時,則可為 7 位或 8 位數字,中間一樣不得有任何其他符號(包含空白或 "-")。

驗證方式是以 JavaScript 的 Regular Expression (RegExp) 物件對照號碼各符號/數字的位置和數目是否符合前述規則。函數 validate_phone_number( phones ) 檢驗 phones 陣列中的各個元素所含電話號碼字串是否符合規則,以傳回 true/false 陣列直接顯示驗證結果。

實際應用上,每一次祗會驗證一個號碼,不需考慮處理陣列, validate_phone_number 的程式片段如下:

function validate_phone_number( phones ) {
   var patt = /^\(0\d{2}\)\d{6}$|^\(0\d{1}\)\d{7,8}$|(^0\d{1})-\d{7,8}$|(^0\d{2})-\d{6}$/
   return patt.test( phones );
}

validate_phone_number( phones ) 的回傳值是 true 或 false,可以協助驗證使用者輸入是否正確。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.