Open In App

Validate Phone Numbers ( with Country Code extension) using Regular Expression

Last Updated : 27 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given some Phone Numbers, the task is to check if they are valid or not using regular expressions. Rules for the valid phone numbers are: 

  • The numbers should start with a plus sign ( + )
  • It should be followed by Country code and National number.
  • It may contain white spaces or a hyphen ( – ).
  • the length of phone numbers may vary from 7 digits to 15 digits.

Examples:

Input:+91 (976) 006-4000 
Output: True

Input: +403 58 59594
Output: True 

Approach: The problem can be solved based on the following idea:

Create a regex pattern to validate the number as written below:   

regex= “^[+]{1}(?:[0-9\-\(\)\/\.]\s?){6, 15}[0-9]{1}$”

Where, 
^ : start of the string

  • [+]{1} :Matches a “+”  character, matches exactly one of the preceding item
  • (?:): :Groups multiple tokens together without creating a capture group.
  • [0-9\-\(\)\/\.] : matches   any character in the set from 0 to 9, “-“, “(“, “)”, “/”, and “.” .
  • \\s : match a white space character
  • ? : matches 0 or 1 of the preceding item.
  • {6, 14} : This expression will match 6 to 14 of the preceding item.
  • [0-9] : This will match values from 0 to 9
  • {1} : This expression will match exactly one of the preceding item.
  • $ : End of the string. 

Follow the below steps to implement the idea:

  • Create a regex expression for phone numbers.
  • Use Pattern class to compile the regex formed.
  • Use the matcher function to check whether the Phone Number is valid or not.
  • If it is valid, return true. Otherwise, return false.

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
#include <regex>
using namespace std;
 
// Function to validate the
// International Phone Numbers
string isValidPhoneNumber(string phonenumber)
{
    // Regex to check valid phonenumber.
    const regex pattern("^[+]{1}(?:[0-9\\-\\(\\)\\/"
                        "\\.]\\s?){6,15}[0-9]{1}$");
 
    // If the phone number is empty return false
    if (phonenumber.empty()) {
        return "false";
    }
 
    // Return true if the phonenumber
    // matched the ReGex
    if (regex_match(phonenumber, pattern)) {
        return "true";
    }
    else {
        return "false";
    }
}
 
// Driver Code
int main()
{
    // Test Case 1:
    string str1 = "+919136812895";
    cout << isValidPhoneNumber(str1) << endl;
 
    // Test Case 2:
    string str2 = "+91 9136812895";
    cout << isValidPhoneNumber(str2) << endl;
 
    // Test Case 3:
    string str3 = "+123 123456";
    cout << isValidPhoneNumber(str3) << endl;
 
    // Test Case 4:
    string str4 = "654294563";
    cout << isValidPhoneNumber(str4) << endl;
 
    return 0;
}


Java




import java.util.regex.*;
 
public class PhoneNumberValidator {
    // Function to validate the International Phone Numbers
    static String isValidPhoneNumber(String phoneNumber) {
        // Regex to check valid phone number.
        String pattern = "^[+]{1}(?:[0-9\\-\\(\\)\\/" +
                         "\\.]\\s?){6,15}[0-9]{1}$";
 
        // If the phone number is empty return false
        if (phoneNumber.isEmpty()) {
            return "false";
        }
 
        // Return true if the phone number
        // matched the Regex
        if (Pattern.matches(pattern, phoneNumber)) {
            return "true";
        } else {
            return "false";
        }
    }
 
    // Driver Code
    public static void main(String[] args) {
        // Test Case 1:
        String str1 = "+919136812895";
        System.out.println(isValidPhoneNumber(str1));
 
        // Test Case 2:
        String str2 = "+91 9136812895";
        System.out.println(isValidPhoneNumber(str2));
 
        // Test Case 3:
        String str3 = "+123 123456";
        System.out.println(isValidPhoneNumber(str3));
 
        // Test Case 4:
        String str4 = "654294563";
        System.out.println(isValidPhoneNumber(str4));
    }
}


Python3




import re
 
# Function to validate the International Phone Numbers
def is_valid_phone_number(phone_number):
    # Regex to check valid phone number.
    pattern = r"^[+]{1}(?:[0-9\\-\\(\\)\\/" \
              "\\.]\\s?){6,15}[0-9]{1}$"
 
    # If the phone number is empty return false
    if not phone_number:
        return "false"
 
    # Return true if the phone number
    # matched the Regex
    if re.match(pattern, phone_number):
        return "true"
    else:
        return "false"
 
# Driver Code
# Test Case 1:
str1 = "+919136812895"
print(is_valid_phone_number(str1))
 
# Test Case 2:
str2 = "+91 9136812895"
print(is_valid_phone_number(str2))
 
# Test Case 3:
str3 = "+123 123456"
print(is_valid_phone_number(str3))
 
# Test Case 4:
str4 = "654294563"
print(is_valid_phone_number(str4))


C#




using System;
using System.Text.RegularExpressions;
 
class Program
{
    // Function to validate the International Phone Numbers
    static string IsValidPhoneNumber(string phoneNumber)
    {
        // Regex to check valid phone number.
        string pattern = @"^[+]{1}(?:[0-9\\-\\(\\)\\/" +
                          "\\.]\\s?){6,15}[0-9]{1}$";
 
        // If the phone number is empty return false
        if (string.IsNullOrEmpty(phoneNumber))
        {
            return "false";
        }
 
        // Return true if the phone number
        // matched the Regex
        if (Regex.IsMatch(phoneNumber, pattern))
        {
            return "true";
        }
        else
        {
            return "false";
        }
    }
 
    // Driver Code
    static void Main(string[] args)
    {
        // Test Case 1:
        string str1 = "+919136812895";
        Console.WriteLine(IsValidPhoneNumber(str1));
 
        // Test Case 2:
        string str2 = "+91 9136812895";
        Console.WriteLine(IsValidPhoneNumber(str2));
 
        // Test Case 3:
        string str3 = "+123 123456";
        Console.WriteLine(IsValidPhoneNumber(str3));
 
        // Test Case 4:
        string str4 = "654294563";
        Console.WriteLine(IsValidPhoneNumber(str4));
    }
}


Javascript




// Function to validate the International Phone Numbers
function isValidPhoneNumber(phoneNumber) {
    // Regex to check valid phone number.
    const pattern = /^[+]{1}(?:[0-9\-\\(\\)\\/.]\s?){6,15}[0-9]{1}$/;
 
    // If the phone number is empty return false
    if (!phoneNumber) {
        return "false";
    }
 
    // Return true if the phone number
    // matched the Regex
    if (pattern.test(phoneNumber)) {
        return "true";
    } else {
        return "false";
    }
}
 
// Driver Code
// Test Case 1:
const str1 = "+919136812895";
console.log(isValidPhoneNumber(str1));
 
// Test Case 2:
const str2 = "+91 9136812895";
console.log(isValidPhoneNumber(str2));
 
// Test Case 3:
const str3 = "+123 123456";
console.log(isValidPhoneNumber(str3));
 
// Test Case 4:
const str4 = "654294563";
console.log(isValidPhoneNumber(str4));


Output

true
true
true
false

Time Complexity: O(N) for each testcase, where N is the length of the given string. 
Auxiliary Space: O(1)  

Related Articles:



Like Article
Suggest improvement
Share your thoughts in the comments