Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

javascript - Regex to allow PhoneNumber with country code

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
+d{1,4}-(?!0)d{1,10}

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
                        Match a word boundary

Demo (with your examples)

var phoneRegexp = /+d{1,4}-(?!0)d{1,10}/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[i] === expected[i]) + ', ';
}
<p id="result"></p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...