Created
February 9, 2015 14:36
-
-
Save twlca/8c8d51b7722885b21b7b to your computer and use it in GitHub Desktop.
Regular Expression Pattern to Check Phone Number
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
驗證輸入的電話或傳真號碼是否正確
可接受的電話號碼格式有:
也就是說區碼本身一定以 "0" 開頭,區碼祇能 2 個或 3 個數字;區碼以 "-" 與本地號碼相隔,或者是區碼界於括弧中,而直接接本地號碼;本地號碼在區碼為 3位數字時,一定為 6 位數字,中間不得有任何其他符號(包含空白或 "-");而本地號碼在區碼為 2 位數字時,則可為 7 位或 8 位數字,中間一樣不得有任何其他符號(包含空白或 "-")。
驗證方式是以 JavaScript 的 Regular Expression (RegExp) 物件對照號碼各符號/數字的位置和數目是否符合前述規則。函數 validate_phone_number( phones ) 檢驗 phones 陣列中的各個元素所含電話號碼字串是否符合規則,以傳回 true/false 陣列直接顯示驗證結果。
實際應用上,每一次祗會驗證一個號碼,不需考慮處理陣列, validate_phone_number 的程式片段如下:
validate_phone_number( phones ) 的回傳值是 true 或 false,可以協助驗證使用者輸入是否正確。