10

Could anyone tell me what RegEx would work to validate an international phone number including white space between the numbers and also allowing for these chars: - ( ).

The amount of numbers in the string is not too important, I would just like the user to be able to type something like either example 1 or 2 if they wish:

Example:

  1. +44 (0) 207 111 1111

  2. 442071111111

I have already read through and tested the posted answers to some similar questions to the best of my understanding but so far none of them are working for me the way I want them to.

Please can someone help me out with a clear explanation of how the above should be written for validation?

Many thanks to anyone who can help.

Passerby
  • 9,715
  • 2
  • 33
  • 50
user2031340
  • 111
  • 1
  • 1
  • 4
  • Example 1 does not match your description. The description doesn't seem to allow a leading `+` – John Dvorak Feb 01 '13 at 04:59
  • Sorry people I missed the '+' in my description. I would like to include this if poss. – user2031340 Feb 01 '13 at 05:01
  • see the link given below for guidance http://stackoverflow.com/questions/6918185/javascript-regular-expression-phone-number-validation http://stackoverflow.com/questions/6195458/phone-number-validation-javascript these questions have the same problem as of yours. so it will give you the solution of your problem. – adeel iqbal Feb 01 '13 at 05:01

9 Answers9

16

Try this code

HTML Code

<input type="text" id="phone"/>

JS Code

$("#phone").blur(function() {
  var regexp = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/
  var no = $("#phone").val();
  if (!regexp.test(no) && no.length < 0) {
    alert("Wrong phone no");
  }
});
Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
Sagar Hirapara
  • 1,677
  • 13
  • 24
  • 1
    I guess the only interesting part here is the regex itself. – John Dvorak Feb 01 '13 at 05:05
  • 2
    My phone number is `112` and your regex claims it's not correct. – John Dvorak Feb 01 '13 at 05:07
  • Thanks for your interest and help man. Below is the code I have so far. Can i not just change the check function to allow for what I want? What do you think? – user2031340 Feb 01 '13 at 05:20
  • function checkNumber(value,nstatus_id){ var reg = /[0-9]/; document.getElementById(nstatus_id).src = (reg.test(value) == false) ? "images/bad.png" : "images/ok.png"; } Contact Number: Status – user2031340 Feb 01 '13 at 05:25
  • sorry dude but i cann't understand actully what u want,please post your question with description and give me your posted question's url – Sagar Hirapara Feb 01 '13 at 05:29
  • My apologies man.. its been a long day! All I want to do is validate a form using the above code. If a user enters the correct information the 'ok' image appears in the form. However if they do not enter the correct information the field remains with an 'X' image next to it. By simply inputting the correct information I would like for the image to change to the 'ok' image. I have this already working for the email address field in my form, however i need to change the check function for the phone number field as of course it requires different criteria. Cheers man. – user2031340 Feb 01 '13 at 05:33
  • I thought that maybe this should be achieved by Regex. But maybe i'm wrong there. – user2031340 Feb 01 '13 at 05:40
  • This regular expression allows unlimited length string if it has more then 6 digests and unlimited -. For example 123--------------------------456. – Milk3dfx May 05 '19 at 02:30
13

See A comprehensive regex for phone number validation

Quick cheat sheet

  • Start the expression: /^
  • If you want to require a space, use: [\s] or \s
  • If you want to require parenthesis, use: [(] and [)] . Using \( and \) is ugly and can make things confusing.
  • If you want anything to be optional, put a ? after it
  • If you want a hyphen, just type - or [-] . If you do not put it first or last in a series of other characters, though, you may need to escape it: \-
  • If you want to accept different choices in a slot, put brackets around the options: [-.\s] will require a hyphen, period, or space. A question mark after the last bracket will make all of those optional for that slot.
  • \d{3} : Requires a 3-digit number: 000-999. Shorthand for [0-9][0-9][0-9].
  • [2-9] : Requires a digit 2-9 for that slot.
  • (\+|1\s)? : Accept a "plus" or a 1 and a space (pipe character, |, is "or"), and make it optional. The "plus" sign must be escaped.
  • If you want specific numbers to match a slot, enter them: [246] will require a 2, 4, or 6. [77|78] will require 77 or 78.
  • $/ : End the expression
Community
  • 1
  • 1
vapcguy
  • 7,097
  • 1
  • 56
  • 52
10

This is a long regex, but it supports both formats (for example 2 to be a valid international number, is MUST start with either + or 00):

/^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/i

This allows extensions and a multiple choice of formats and separators.

Matches:

  • (+351) 282 43 50 50
  • 90191919908
  • 555-8909
  • 001 6867684
  • 001 6867684x1
  • 1 (234) 567-8901
  • 1-234-567-8901 x1234
  • 1-234-567-8901 ext1234
  • 1-234 567.89/01 ext.1234
  • 1(234)5678901x1234
  • (123)8575973
  • (0055)(123)8575973

On $n, it saves:

  1. Country indicator
  2. Phone number
  3. Extention

This same answer was given here: A comprehensive regex for phone number validation (direct link to my answer)

Community
  • 1
  • 1
Ismael Miguel
  • 4,185
  • 1
  • 31
  • 42
  • 1
    @JeanPaul Very helpful... Can you please tell me what's wrong? – Ismael Miguel Apr 09 '14 at 13:19
  • This is very helpful. Working well for me. Thanks – Ankit Sahrawat Sep 08 '14 at 07:05
  • @AnkitSahrawat You are welcome. If you find any case that should be validated but it's not, you can always comment here and I will fix it. – Ismael Miguel Sep 08 '14 at 08:54
  • I thought this was a little too lenient, so I combined the extension part of it with the @Sagarpatal's answer to create this regex: `/^[\s()+-]*([0-9][\s()+-]*){6,20}(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/i` which works for most cases and requires more than a few digits. – Mordred Jan 23 '15 at 00:05
  • @Mordred That surely seems like a nice one! It's easier tor ead than mine, doesn't look hacky and it's actually clean (considering the subject). – Ismael Miguel Jan 23 '15 at 00:46
1
/*
@isValidUSPhoneFormat function will check valid US Format
    Allowed US Format
(123) 456-7890
123-456-7890
123.456.7890
1234567890
(734) 555.1212
*/   

    function isValidUSPhoneFormat(elementValue){  
            var phoneNumberPattern = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s.]{0,1}[0-9]{3}[-\s.]{0,1}[0-9]{4}$/;  
            if(phoneNumberPattern.test(elementValue) == false)
            {
                 var phoneNumberPattern = /^(\()?\d{3}(\))?(.|\s)?\d{3}(.|\s)\d{4}$/; 
                 return phoneNumberPattern.test(elementValue);   
            }
            return phoneNumberPattern.test(elementValue);  
        }

May this will help you to understand JavaScript RegEx..

Pank
  • 13,800
  • 10
  • 32
  • 45
1

Don't even try. Trying to guard against what you think is invalid input can result in angry users who can't enter perfectly valid phone numbers. And if the user really wants to enter an invalid phone number, he/she will be able to do it anyway.

Martin Vilcans
  • 5,428
  • 5
  • 22
  • 17
0
function checkPhoneNumber(val) {
    var num = document.getElementById(val).value;
    var mob=/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g;
    if (mob.test(num) == false) {
        alert("Please Enter Valid Phone Number.");
        document.getElementById(val).value = "";
        return false;
    }
     if (num.length > 15) {
        alert("Only 15 characters allowed for Phone Number field.");
        document.getElementById(val).value = "";
        return false;
    }

    return true;
}

Try it Ones

shafi7468
  • 323
  • 1
  • 3
  • 15
0

Try using isValidPhoneNumber(phoneNumber, countryCode) method of libphonenumber-js package. First is the phone number with "+" at the start of it. The second argument is the country code (for eg: 'US', 'IN'). That helps you validate any international number accurately.

0

Best lib for international phone number: google/libphonenumber

Here is an example with CDN:

<script src="https://cdn.jsdelivr.net/npm/google-libphonenumber@3/dist/libphonenumber.min.js"></script>
// Format Phone Number
function formatPhone(p) {
  var phoneUtil = libphonenumber.PhoneNumberUtil.getInstance();
  var parsedPhone = phoneUtil.parse(p);

  if (phoneUtil.isValidNumber(parsedPhone)) {
    return phoneUtil.format(parsedPhone, libphonenumber.PhoneNumberFormat.INTERNATIONAL)
  } else {
    return NaN
  }
}
Efraim
  • 43
  • 6
0

A better option to validate international phone numbers in a loose way is as follows.This is not a strict validation

/^\s*(?:+?(\d{1,3}))?([-. (](\d{3})[-. )])?((\d{3})[-. ](\d{2,4})(?:[-.x ](\d+))?)\s*$/gm

A working Javascript function will look like this

function validatePhone(phone) {
    var regex = /^\s*(?:\+?(\d{1,3}))?([-. (]*(\d{3})[-. )]*)?((\d{3})[-. ]*(\d{2,4})(?:[-.x ]*(\d+))?)\s*$/gm;
    return regex.test(phone);
}
console.log(validatePhone('+973 11111111')) // true
console.log(validatePhone('+973 XX77yyss')) // false

For those who wish to have more about the characters:

  • ^ asserts position at the start of a line
  • \s matches any whitespace character (equivalent to [\r\n\t\f\v ])
  • * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    Non-capturing group (?:+?(\d{1,3}))?
  • ? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
  • + matches the character + with index 4310 (2B16 or 538) literally (case sensitive)
  • ? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
    1st Capturing Group (\d{1,3})
  • \d matches a digit (equivalent to [0-9])
  • {1,3} matches the previous token between 1 and 3 times, as many times as possible, giving back as needed (greedy)
    2nd Capturing Group ([-. (](\d{3})[-. )])?
  • ? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
    Match a single character present in the list below [-. (]
  • * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  • -. ( matches a single character in the list -. ( (case sensitive) 3rd Capturing Group (\d{3})
  • \d matches a digit (equivalent to [0-9])
  • {3} matches the previous token exactly 3 times
    Match a single character present in the list below [-. )]
  • * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  • -. ) matches a single character in the list -. ) (case sensitive)
    4th Capturing Group ((\d{3})[-. ](\d{2,4})(?:[-.x ](\d+))?)
    5th Capturing Group (\d{3})
  • \d matches a digit (equivalent to [0-9])
  • {3} matches the previous token exactly 3 times
    Match a single character present in the list below [-. ]
  • * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  • -. matches a single character in the list -. (case sensitive)
    6th Capturing Group (\d{2,4})
  • \d matches a digit (equivalent to [0-9])
  • {2,4} matches the previous token between 2 and 4 times, as many times as possible, giving back as needed (greedy)
    Non-capturing group (?:[-.x ]*(\d+))?
  • ? matches the previous token between zero and one times, as many times as possible, giving back as needed (greedy)
    Match a single character present in the list below [-.x ]
  • * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  • -.x matches a single character in the list -.x (case sensitive)
    7th Capturing Group (\d+)
  • \d matches a digit (equivalent to [0-9])
  • + matches the previous token between one and unlimited times, as many times as possible, giving back as needed (greedy)
  • \s matches any whitespace character (equivalent to [\r\n\t\f\v ])
  • * matches the previous token between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  • $ asserts position at the end of a line

This would test positive for the below patterns and more
+42 555.123.4567 +1-(800)-123-4567 +7 555 1234567 +7(926)1234567 (926) 1234567 +79261234567 926 1234567 9261234567 1234567 123-4567 123-89-01 495 123

Nafsin Vk
  • 519
  • 4
  • 9