Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
Like Article
  • Last Updated : 14 Dec, 2022
Improve Article
Save Article
Like Article

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++

// C++ program to validate international Phone Numbers
// using Regular Expression

#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

// Java program to validate the
// International Phone Numbers  using Regular
// Expression

import java.util.regex.*;
import java.io.*;

class GFG {

    // Function to validate the
    // International Phone Numbers
    public static boolean
    isValidPhoneNumber(String phonenumber)
    {
        // Regex to check valid phonenumber
        String regex
            = "^[+]{1}(?:[0-9\\-\\(\\)\\/\\.]\\s?){6, 15}[0-9]{1}$";

        // Compile the ReGex
        Pattern p = Pattern.compile(regex);

        // If the phonenumber
        // is empty return false
        if (phonenumber == null) {
            return false;
        }

        // Pattern class contains matcher()
        // method to find matching between
        // given phone number  using regex
        Matcher m = p.matcher(phonenumber);

        // Return if the phonenumber
        // matched the ReGex
        return m.matches();
    }

    // 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

# Python3 program to validate
# International Phone Numbers using Regex
import re

# Function to validate
# International Phone Numbers
def isValidPhoneNumber(str):

    # Regex to check valid International
    # Phone Numbers
    regex = "^[+]{1}(?:[0-9\\-\\(\\)\\/\\.]\\s?){6, 15}[0-9]{1}$"

    # Compile the ReGex
    p = re.compile(regex)

    # If the string is empty
    # return false
    if (str == None):
        return "false"

    # Return if the string
    # matched the ReGex
    if(re.search(p, str)):
        return "true"
    else:
        return "false"


# Driver code
if __name__ == '__main__':
    
    # Test Case 1:
    str1 = "+919136812895"
    print(isValidPhoneNumber(str1))
    
    # Test Case 2:
    str2 = "+91 9136812895"
    print(isValidPhoneNumber(str2))
    
    # Test Case 3:
    str3 = "+123 123456"
    print(isValidPhoneNumber(str3))
    
    # Test Case 4:
    str4 = "654294563"
    print(isValidPhoneNumber(str4))

C#

// C# program to validate the
// International Phone Numbers using Regular
// Expression
using System;
using System.Text.RegularExpressions;

public class GFG {

  // Function to validate the
  // International Phone Numbers
  public static bool
    isValidPhoneNumber(string phonenumber)
  {
    // Regex to check valid phonenumber
    string regex
      = "^[+]{1}(?:[0-9\\-\\(\\)\\/\\.]\\s?){6, 15}[0-9]{1}$";

    // Compile the ReGex
    Regex p = new Regex(regex);

    // If the phonenumber
    // is empty return false
    if (phonenumber == null) {
      return false;
    }

    // Pattern class contains matcher()
    // method to find matching between
    // given phone number using regex
    Match m = p.Match(phonenumber);

    // Return if the phonenumber
    // matched the ReGex
    return m.Success;
  }

  // Driver Code.
  public static void Main()
  {
    // 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));
  }
}

// This code is contributed by Pushpesh Raj.

Javascript

// Javascript program to validate
// International Phone Numbers using Regular Expression

// Function to validate the
// International Phone Numbers
function isValidPhoneNumber(phonenumber) {
    // Regex to check valid
    // International Phone Numbers
    let regex = new RegExp(/^[+]{1}(?:[0-9\-\(\)\/\.]\s?){6, 15}[0-9]{1}$/);

    // if phonenumber
    // is empty return false
    if (phonenumber == null) {
        return "false";
    }

    // Return true if the phonenumber
    // matched the ReGex
    if (regex.test(phonenumber) == true) {
        return "true";
    }
    else {
        return "false";
    }
}

// Driver Code
// Test Case 1:
let str1 = "+919136812895";
console.log(isValidPhoneNumber(str1));

// Test Case 2:
let str2 = "+91 9136812895";
console.log(isValidPhoneNumber(str2));

// Test Case 3:
let str3 = "+123 123456";
console.log(isValidPhoneNumber(str3));

// Test Case 4:
let str6 = "654294563";
console.log(isValidPhoneNumber(str6));

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:


My Personal Notes arrow_drop_up
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!