简体   繁体   中英

Regular Expression Phone Number Validation

I wrote this regular expression for the Lebanese phone number basically it should start with

00961 or +961 which is the international code then the area code which

could be either any digit from 0 to 9 or cellular code "70" or "76" or

"79" then a 6 digit number exactly

I have coded the following reg ex without the 6 digit part :

^(([0][0]|[+])([9][6][1])([0-9]{1}|[7][0]|[7][1]|[7][6]|[7][8]))$

when i want to add code to ensure only 6 digits more are allowed to the expression:

^(([0][0]|[+])([9][6][1])([0-9]{1}|[7][0]|[7][1]|[7][6]|[7][8])([0-9]{6}))$

It Seems to accept 5 or 6 digits not 6 digits exactly

i am having difficulty finding whats wrong

使用这个正则表达式((00)|(\\+))961((\\d)|(7[0168]))\\d{6}

Ths is what I would use.

/^(00|\+)961(\d|7[069])\d{6}$/
  • 00 or +
  • 961
  • a 1-digit number or 70 or 76 or 79
  • a 6-digit number

[0-9]{1}也将匹配蜂窝代码7x,因为7介于0和9之间。这意味着“5位蜂窝数”将匹配7位数和6位数。

Try

 /^(00961|\+961)([0-9]|70|76|79)\d{6}$/.test( phonenumber );
//^                                    start of string
// ^^^^^^^^^^^^^                       00961 or +0961
//              ^^^^^^^^^^^^^^^^       a digit 0 to 9 or 70 or 76 or 79
//                              ^^^^^  6 digits
//                                   ^ end of string

The cellar code is forming a trap, as @ellak points out:

/^((00)|(\+))961((\d)|(7[0168]))\d{6}$/.test("009617612345"); // true

Here the code should breaks like this: 00 961 76 12345 ,

but the RegEx practically breaks it like this: 00 961 7 612345 , because 7 is matched in \\d , and the rest is combined, exactly in 6 digits, and matched.

I'm not sure if this is actually valid, but I guess this is not what you want, otherwise the RegEx in your question should work.

Here's a kinda long RegEx that avoids the trap:

/^(00|\+)961([0-68-9]\d{6}|7[234579]\d{5}|7[0168]\d{6})$/

A few test result:

/(00|\+)961([0-68-9]\d{6}|7[234579]\d{5}|7[0168]\d{6})/.test("009617012345")
  false
/(00|\+)961([0-68-9]\d{6}|7[234579]\d{5}|7[0168]\d{6})/.test("009618012345")
  true
/(00|\+)961([0-68-9]\d{6}|7[234579]\d{5}|7[0168]\d{6})/.test("009617612345")
  false
/(00|\+)961([0-68-9]\d{6}|7[234579]\d{5}|7[0168]\d{6})/.test("0096176123456")
  true

Just recently, the Lebanese Ministry of Telecommunication has changed area codes on the IMS. So the current Regex matcher becomes:

^(00|\+)961[ -]?(2[1245789]|7[0168]|8[16]|\d)[ -]?\d{6}$
  • Prefix: 00 OR +
  • Country code: 961
  • Area code: 1-digit or 2-digits; including 2 *, 7 *, 8 *..., OR a single digit for Ogero numbers on the old IMS network starting with 0 *, and finally older mobile lines starting with 03 .
  • The 6-digit number

News on the961.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM