Pattern for validating mobile numbers with extensions using regular expressions

I am struggling to combine multiple separate regex validations into one for my mobile number validation requirements. The criteria include validating mobile numbers with a country code or starting with 00, as well as checking if they contain an extension number (2-5 digits) separated by a #.

Here is an example of a valid number:

+919986040933
00919986040933
+919986040933#12
+919986040933#123
+919986040933#1234
+919986040933#12345

The current regex patterns I have for validation are:

var phoneRegexWithPlus = "^((\\+)|(00))[0-9]{10,14}$";
var phoneRegexWithZero = "^((\\+)|(00))[0-9]{9,12}$";
var phoneRegexExtension = "^[0-9]{2,5}$";

Currently, I am checking whether the number contains a # symbol, and if so, splitting it to match the number and extension parts separately where the extension comes after the hash.

My challenge now is to create a single regex that combines all three validations above. Can anyone help me with this as I am not proficient in regex? Thank you in advance.

Answer №1

Here is a suggested expression for you:

^\+?(?:00)?\d{12}(?:#\d{2,5})?$

If you want to see how this regex works in action, check out the regex demo

Explanation of the Expression:

  • ^ - signifies the start of the string
  • \+? - represents an optional plus sign (the ? allows for zero or one occurrence)
  • (?:00)? - indicates an optional occurrence of 00
  • \d{12} - specifies exactly 12 digits in a row
  • (?:#\d{2,5})? - denotes an optional sequence where:
    • # - denotes a literal hash symbol
    • \d{2,5} - matches between 2 to 5 digits (which could represent your specific phoneRegexExtension)
  • $ - marks the end of the string.

The essential parts covered by both phoneRegexWithPlus and phoneRegexWithZero are included in the initial segment \+?(?:00)?\d{12}, which matches 12 to 14 digits with an optional plus sign at the beginning.

NOTE: This regex has been tailored to fit the sample input provided. If the input varies, you may need to adjust the limiting quantifiers like {12} to a range such as {9,14} to accommodate 9 to 14 occurrences of the specified pattern.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to display an image along with a description using Firebase and next.js?

I am currently utilizing Firebase 9 and Next.js 13 to develop a CRUD application. I am facing an issue where the images associated with a post are not correctly linked to the post ID. Furthermore, I need guidance on how to display these images in other com ...

Is it advisable to implement the modular pattern when creating a Node.js module?

These days, it's quite common to utilize the modular pattern when coding in JavaScript for web development. However, I've noticed that nodejs modules distributed on npm often do not follow this approach. Is there a specific reason why nodejs diff ...

The quiet harmony of FeathersJS and Socket.io as they attentively listen to events is

I've been working hard to get everything set up and running smoothly, but it seems like I'm stuck on the last piece of the puzzle. Despite following the documentation closely, I can't seem to figure out what I'm missing. Here is the @an ...

Struggling with passing data to a child component in React

I am currently working on a gallery project where users can click on an image to view it in a separate component using props. The images are sourced from a hardcoded array, and the challenge lies in connecting this data to the component accurately. I have ...

Unexpected bug encountered while implementing redux

I received a warning from eslint while working with create-react-app. ./src/components/auth.js Line 24: Unexpected labeled statement no-labels Line 24: 'authenticated:' is defined but never used ...

In JavaScript, promises remain in a pending state

How can I prevent my promises from remaining in the pending state and resolve them instead? var foundPeopleA = findPeopleA().then(function(result) { var res = [] result.map(function(el) { res.push(getProfileXML(el.sid)); ...

Setting up a connection between an Express server and a Mongoose database in

As someone who is relatively new to the express framework and mongoose database, I have mainly worked with relational databases in the past. I am attempting to create a database using the script below. Currently, mongod.exe is running and listening on loca ...

Incorporating PruneCluster into an AngularJS Leaflet Directive for Enhanced Mapping

I am currently facing an issue with loading clustered markers for geojson data using PruneCluster. The clusters are not appearing on the map and there are no errors showing up in the console to assist with troubleshooting. Below is the snippet of my curr ...

React Redux - There is an error during rendering as expected props have not been received yet

After retrieving data from an API and storing it in the Redux state, I utilize a helper function within mapStateToProps to filter and modify a portion of that data before passing it along as props. Although everything appears to be functioning correctly b ...

Getting Session from Next-Auth in API Route: A Step-by-Step Guide

When printing my session from Next Auth in a component like this, I can easily see all of its data. const session = useSession(); // ... <p>{JSON.stringify(session)}</p> I am facing an issue where I need to access the content of the session i ...

Clear out a collection in backbone.js

I am looking to clear out a collection by removing each item in sequence. this.nodes.each(function(node){ this.nodes.remove(node); }, this); The current method is ineffective as the collection length changes with each removal. Utilizing a temporary arr ...

What is the best way to send an XML body using Angular 5 with POST method?

I am currently developing an Ionic application that needs to make REST API calls with XML as the body. However, I am facing issues in getting the call to post with XML. This is my LoginProvider where I utilize DOMParser to parse data to XML before sending ...

The function 'create' is not a recognized property within the 'Completions' type

Recently, I've been experimenting with ChatGPT and have just installed the latest version 4.8.0. My current project is built on NextJS. Prior to this, I successfully completed a project using v3.something last month, but I'm encountering diffic ...

Best Practices for Utilizing NPM Modules with TypeScript

I am interested in developing an npm module using TypeScript. Can anyone suggest a best practice guide on how to start? Here are my questions: Node.js does not natively support TypeScript, so what is the recommended way to publish an npm module? Shoul ...

Monitoring progress with Angular $http and $q

Is there a method to monitor the progress of http requests using Angular's $http and $q services? I am sending multiple $http calls from a list of URLs and then utilizing $q.all to gather the results of all the requests. I want to keep track of the pr ...

"Using Mxgraph's getPrettyXml function does not retrieve the value of a custom

I’m having trouble with mxgraph’s getPrettyXml() not capturing the value of Custom elements. In my customized template, it looks like this: <add as="symbol"> <Symbol label="Symbol" description="" href="" data="{[hi :bill]}"> &l ...

Why does Cloudinary fail to delete the tmp folder it creates after finishing the upload process?

Recently, I've been working on implementing an upload Post feature for my app. The process involves submitting a file from the frontend, sending it to the backend, and then uploading it to Cloudinary's cloud servers. However, before the upload to ...

AJAX - Implementing a delay in displaying AJAX results

My search function uses AJAX to retrieve data from the web-server, and I am trying to implement a fade-in animation for each search result. I want the results to load and fade in one by one with a slight delay between them. Currently, it seems like all th ...

Extracting a subclass from an array

Currently, I am delving into the world of coding as part of a project I'm working on. Here is an excerpt from my JavaScript code that interacts with Google Maps API: for (i = 0; i < results.length; i++) { console.log("Formatted Address: "+ re ...

AngularJS attempting to conceal the popup menu upon clicking outside of the designated area

My HTML structure looks like this: <div> <a href="" ng-click="$scope.show_menu = !$scope.show_menu">Options</a> <div class="options_box" ng-show="$scope.show_menu"> <button>Option1</button> ... ...