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

Table of Contents
C++ Java Python3 C# Javascript References

Last Updated : 27 Dec, 2023

Improve

Improve

Like Article

Like

Save

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

truetruetruefalse

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

Related Articles:

  • How to write Regular Expressions?
  • Program to find all match of a regex in a string


`; tags.map((tag)=>{ let tag_url = `videos/${getTermType(tag['term_id__term_type'])}/${tag['term_id__slug']}/`; tagContent+=``+ tag['term_id__term_name'] +``; }); tagContent+=`
`; return tagContent; } //function to create related videos cards function articlePagevideoCard(poster_src="", title="", description="", video_link, index, tags=[], duration=0){ let card = `

${secondsToHms(duration)}

${title}
${showLessRelatedVideoDes(htmlToText(description))} ... Read More

${getTagsString(tags)}

`; return card; } //function to set related videos content function getvideosContent(limit=3){ videos_content = ""; var total_videos = Math.min(videos.length, limit); for(let i=0;i

'; } else{ let view_all_url = `${GFG_SITE_URL}videos/`; videos_content+=`

View All

`; } // videos_content+= '

'; } } return videos_content; } //function to show main video content with related videos content async function showMainVideoContent(main_video, course_link){ //Load main video $(".video-main").html(`

`); require(["ima"], function() { var player = videojs('article-video', { controls: true, // autoplay: true, // muted: true, controlBar: { pictureInPictureToggle: false }, playbackRates: [0.5, 0.75, 1, 1.25, 1.5, 2], poster: main_video['meta']['largeThumbnail'], sources: [{src: main_video['source'], type: 'application/x-mpegURL'}], tracks: [{src: main_video['subtitle'], kind:'captions', srclang: 'en', label: 'English', default: true}] },function() { player.qualityLevels(); try { player.hlsQualitySelector(); } catch (error) { console.log("HLS not working - ") } } ); const video = document.querySelector("video"); const events =[ { 'name':'play', 'callback':()=>{videoPlayCallback(main_video['slug'])} }, ]; events.forEach(event=>{ video.addEventListener(event.name,event.callback); }); }, function (err) { var player = videojs('article-video'); player.createModal('Something went wrong. Please refresh the page to load the video.'); }); /*let video_date = main_video['time']; video_date = video_date.split("/"); video_date = formatDate(video_date[2], video_date[1], video_date[0]); let share_section_content = `

${video_date}

`;*/ let hasLikeBtn = false; // console.log(share_section_content); var data = {}; if(false){ try { if((loginData && loginData.isLoggedIn == true)){ const resp = await fetch(`${API_SCRIPT_URL}logged-in-video-details/${main_video['slug']}/`,{ credentials: 'include' }) if(resp.status == 200 || resp.status == 201){ data = await resp.json(); share_section_content+= `

`; hasLikeBtn = true; } else { share_section_content+= `

`; } } else { share_section_content+= `

`; } //Load share section // $(".video-share-section").html(share_section_content); // let exitCond = 0; // const delay = (delayInms) => { // return new Promise(resolve => setTimeout(resolve, delayInms)); // } // while(!loginData){ // let delayres = await delay(1000); // exitCond+=1; // console.log(exitCond); // if(exitCond>5){ // break; // } // } // console.log(loginData); /*if(hasLikeBtn && loginData && loginData.isLoggedIn == true){ setLiked(data.liked) setSaved(data.watchlist) }*/ } catch (error) { console.log(error); } } //Load video content like title, description if(false){ $(".video-content-section").html(`

${main_video['title']}

${hideMainVideoDescription(main_video['description'], main_video['id'])}

${getTagsString(main_video['category'])} ${(course_link.length)? `

View Course

`:''} `); let related_vidoes = main_video['recommendations']; if(!!videos && videos.length>0){ //Load related videos $(".related-videos-content").html(getvideosContent()); } } //show video content element = document.getElementById('article-video-tab-content'); element.style.display = 'block'; $('.spinner-loading-overlay:eq(0)').remove(); $('.spinner-loading-overlay:eq(0)').remove(); } await showMainVideoContent(video_data, course_link); // fitRelatedVideosDescription(); } catch (error) { console.log(error); } } getVideoData(); /* $(window).resize(function(){ onWidthChangeEventsListener(); }); $('#video_nav_tab').click('on', function(){ fitRelatedVideosDescription(); });*/ });

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

References

Top Articles
Latest Posts
Article information

Author: Pres. Carey Rath

Last Updated:

Views: 6366

Rating: 4 / 5 (41 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Pres. Carey Rath

Birthday: 1997-03-06

Address: 14955 Ledner Trail, East Rodrickfort, NE 85127-8369

Phone: +18682428114917

Job: National Technology Representative

Hobby: Sand art, Drama, Web surfing, Cycling, Brazilian jiu-jitsu, Leather crafting, Creative writing

Introduction: My name is Pres. Carey Rath, I am a faithful, funny, vast, joyous, lively, brave, glamorous person who loves writing and wants to share my knowledge and understanding with you.