ECM
ECM
总版主
总版主
  • 社区居民
  • 忠实会员
  • 原创写手
阅读:624回复:0

Regex to allow PhoneNumber with country code

楼主#
更多 发布于:2016-05-30 21:31
I need a regex to validate a phone number (With country code )which shall follow the below conditions 1 - There should be at max 4 digits in between + and - .
2 - Phone number shall be a combination of +,- and digits
3 - 0 shall not be allowed after -
4 - After - only 10 digits are allowed
 E.g     1 - +91234-1234567 - Fail (1st Condition fails)
    2 - +9123-1234567  - Pass
    3 - +               - Fail (2nd condition fails)
    4 - -               - Fail (2nd condition fails)
    5 - 91234545555     - Fail (2nd condition fails)
    6 - +91-012345      - Fail (3rd Condition fails)
    7 - +91-12345678910 - Fail (4th condition fails)
 Please help me in this .Thanks in advance.
answer(解决方案):

\+\d{1,4}-(?!0)\d{1,10}\b
 Breakdown: \+                        Match a literal +
\d{1,4}                   Match between 1 and 4 digits inclusive
-                         Match a literal -
(?!                       Negative lookahead, fail if
  0                       this token (literal 0) is found
)
\d{1,10}                  Match between 1 and 10 digits inclusive
\b                        Match a word boundary
 Demo (with your examples) var phoneRegexp = /\+\d{1,4}-(?!0)\d{1,10}\b/g,
  tests = [
    '+91234-1234567',
    '+9123-1234567',
    '+',
    '-',
    '91234545555',
    '+91-012345',
    '+91-12345678910'
  ],
  results = [],
  expected = [false, true, false, false, false, false, false];

results = tests.map(function(el) {
  return phoneRegexp.test(el);
});

for (var i = 0; i < results.length; i++) {
  document.getElementById('result').textContent += (results === expected) + ', ';
} <p id="result"></p>

 

 

 

 

 

 

 

异常中心网是一家专门收集整理程序员编程过程中遇到的常见异常(exception)以及各种异常问答中心的网站。异常中心网旨在,减少程序员在编码遇到异常,处理各种异常时间和痛苦,让程序员能更愉快的、快速的定位异常并查找对应的异常解决方案。异常中心网诚心打造最完美的编程社区为程序员用户服务,努力成为最好的程序员乐园程序员社区程序异常中心程序bug中心异常问答中心

 

喜欢0 评分0
游客

返回顶部