BhavikKama
BhavikKama

Reputation: 8800

regex for phone number validation?

i want to validate my phone number with the regex for following formats.i have googled the things but i could not find the regex for following formats...

    079-26408300 / 8200
    (079) 26408300
    079 264 083 00 
    9429527462

can anyone please guide me how can i do validate the phone number field for above formats? I want to validate the phone number for only above formats as right now am using only following regex var phone_pattern = /^[a-z0-9]+$/i;

@Ali Shah Ahmed

var phone_pattern = "(\d{10})|(\d{3}-\d{8}\s/\s\d{4})|((\d{3}\s){3}\d{2})|((\d{3})\s\d{8})";

here is the way am checking if its valid

if (!phone_pattern.test(personal_phone))
        {
            $("#restErrorpersonalphone").html('Please enter valid phone number');
            $("#personal_phone").addClass('borderColor');
            flag = false;
        } else {
            $("#restErrorpersonalphone").html('');
            $("#personal_phone").removeClass('borderColor');
        }

its not working. Am I implementing in wrong way?

Upvotes: 0

Views: 682

Answers (2)

Ali Shah Ahmed
Ali Shah Ahmed

Reputation: 3333

lets start with the simplest phone number 9429527462
As this has 10 characters and all are numbers, regex for it could be \d{10}

Now the next phone number 079 264 083 00. Regex for this pattern could be (\d{3}\s){3}\d{2} First we are expecting a group of 3 digits and a space to repeat thrice (\d{3}\s){3}, this will cover 079 264 083 (space included in it), so left will be the last two characters which are handled using \d{2}

For the phone number (079) 26408300, \(\d{3}\)\s\d{8} regex could be use. The regex first looks for a opening bracket, then three digits inside it, and then the closing bracket. It then looks for a space, and then for 8 digits.

The phone number 079-26408300 / 8200 could be validated using regex \d{3}-\d{8}\s/\s\d{4}. It first looks for 3 digits then a -, then 8 digits followed by a space. Then looks for a / and then a space and then 4 digits.

If you wish to know a single regex for validating all the above patterns, do let me know.

Final combined regex would be:

/(\d{10})|(\d{3}-\d{8}\s\/\s\d{4})|((\d{3}\s){3}\d{2})|(\(\d{3}\)\s\d{8})/

Upvotes: 1

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136102

Straightforward solution is simple, use |

String ex = "\\d{3}-\\d{8} / \\d{4}|\\(\\d{3}\\) \\d{8}|...

Upvotes: 0

Related Questions