JavaScript regex for UK cell phone numbers

I am currently implementing the following:

phone_number.match(/^((\+44\s?|0)7([45789]\d{2}|624)\s?\d{3}\s?\d{3})$/);

In most cases, the above code works well. Valid formats include:

07714000000 +447714000000

However, I also need to allow the format without the plus sign, for example:

447714000000

I tried adding a "?" between the "+" and "44", which worked in an online tester but not in JavaScript.

How can I achieve this?

Thank you

Update I am using this in the JQuery Validation plugin, here is the code:

jQuery.validator.addMethod('mobileUK', function(phone_number, element) {
    return this.optional(element) || phone_number.length > 9 &&
        phone_number.match(/^((\+?44\s?|0)7([45789]\d{2}|624)\s?\d{3}\s?\d{3})$/);
}, 'Please specify a valid mobile number');

It functions normally without the "?", but does not match with just "44".

Answer №1

Your regular expression is accurate.

To enhance the flexibility of your regex, consider allowing spaces within the string. One approach could be to remove all non-numeric characters, eliminating the need to check for +.

For example

var mobileNumberRegex = /^(?:(?:00)?44|0)7(?:[45789]\d{2}|624)\d{6}$/;
if (phoneNumber.replace(/\D/g, '').test(mobileNumberRegex)) alert('Phone number is valid!');

Please note: The provided regular expression also validates numbers formatted as 00447714000000.

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

Destructuring part of an object within function parameters in JavaScript

Is it possible to selectively destructure specific object properties in function arguments, while keeping the rest accessible within the object? Let's explore this concept with a React example. (Although React is used here, the question pertains to J ...

Initiate the python script on the client's end

Currently, I am in the process of initiating a Python script designed to parse a CSV file that has been uploaded by the user through the UI. On the client side, how can I effectively trigger the Python script (I have explored using AJAX HTTP requests)? Add ...

Is there a way to retrieve the data inputted into dynamically generated input boxes and send it to the controller using jQuery?

I am working on a form that allows users to enter input boxes and remove them with a click. I need help extracting the values entered in these input boxes and passing them to a controller using jQuery. Currently, I am using ids to extract the values but I ...

The .AppendChild() method does not appear to be working as expected following the completion of

Encountering a peculiar problem here. The scripts run smoothly, but the content doesn't display on screen until I "inspect element" and then close the inspector window or zoom in/out. It's not an issue with the "display" CSS property because even ...

I am eager to run the code that I retrieved from the server. I have access to the code in my console and I desire for it to execute on the main browser page

Currently, I have a simple Google Chrome Extension that includes a button. By using AJAX, I am fetching a script from a server in my browser's console. Essentially, clicking on the extension reveals a button which, when clicked, fetches the script fro ...

Commitments do not come with a collections feature

Struggling to implement the collection method, it seems that I can't directly use db.collection as db is calling connectDB, which returns conn, my mongoURI, as a promise. How can I modify this setup to effectively utilize the collection method and sen ...

What could be the reason for my Angular component not updating its value?

component1.html : <div class="nums-display"> {{nums}} </div> TS: nums: Array<number> = [0, 1, 2, 3]; ngOnInit(): void { this.numService.getNum().subscribe((res) => { this.num = res; }); } component2.html: <div (cli ...

Using Javascript to add the current date and time into a mysqli query

Currently, I have a database setup with a datetime data type for landing time. I am trying to achieve this using Javascript. The format in the database appears as: 0000-00-00 00:00:00 I have made an attempt with the following code: $('#landing_tim ...

Why is Joi validation triggering an error when dealing with a nested object? Could this issue be connected to the use of dot notation in the

I am facing an issue with my joi validation when trying to submit a form. The error message I receive is: STACK: Error: "author.surname" is not allowed at module.exports.citationJoi Upon reviewing my joiSchema, everything seems correct: const n ...

Tips on creating a slow and gradual border animation that unfolds smoothly

I am looking to create an animation effect on a border, gradually revealing it like in this Codepen example. However, my specific requirements are: The previous line should not be removed, but rather shown along with the new border. The border color ...

Leveraging PrimeFaces and the p:ajax component, trigger Ajax within an inputText field only when keystrokes lead to changes in the field

I am currently utilizing PrimeFaces and have a p:inputText field that requires updating certain components on the view based on the most recent keystroke within that p:inputText. Below is the code snippet: <p:inputText value="#{customerLController.surn ...

Using Vue.js to set both v-model and v-bind:value on one input element

I have a React component that has a form for submitting user information. The main issue I'm facing is setting a default value in the input field. When the page loads, I want the input field to display the user's existing email address by defaul ...

What could be causing this issue to not function properly in JavaScript?

Here is a JavaScript code snippet that I am working on: var inx=[2,3,4,5]; var valarray=[]; for (i=0; i<inx.length; i++) { valarray[i]==inx[i]; } for (i=0; i<inx.length; i++) { var posi=inx.indexOf(3); var valy=valarray[posi-1]+1; v ...

Encountering "Uncaught TypeError: Cannot read properties of undefined" while trying to render data in React, with some data rendering correctly and others throwing errors

I am currently developing an online magazine using React, similar to popular publications like Vogue and Elle. In my project, I have a JavaScript file that serves as an API for the data, containing an array of objects. Each object within the array represen ...

The Node.js application that uses Express and connects to a MSSQL database is reporting that the database

One of my other applications utilizes express and routes, but for this new app I wanted to simplify it. Despite being confident in the correctness of the connection string, I encountered an issue. script.getQuestions(connection); script.getQuestions = fu ...

Transforming an object into an array of objects with the power of JavaScript

Looking to transform an object with the following structure: { From: {"A","B","C"}, To: {"A1","B1","C1"}, value: {1,2,3} } I need to convert this array: [ {from: "A" ,to: "A1" , value: 1 }, {from: "B" ,to: "B1" , value: 2}, {from: "C" ,to: "C1" ...

Fade out a dynamically loaded content block using jQuery

I am currently developing a small app and encountering issues with deleting (fading out) dynamically loaded div elements using jQuery. The problem occurs when adding a new content box. If the page is reloaded and the content box is rendered normally (from ...

How to design a dictionary schema using Mongoose

I have been attempting to save a dictionary of objects using Mongoose. Upon realizing that the change detection for saving is lost when using the Mixed type, I am looking for a way to create a schema that does not rely on the Mixed type. While there are m ...

"Can you explain the functioning of this Node.js middleware when it doesn't require any

Currently, I am utilizing a function created by another individual for express and passport, which defines the middleware in the following manner: function isLoggedIn(req, res, next) { if (req.isAuthenticated()){ return next(); } els ...

The timer freezes briefly at 1:60 before switching to 1:01

I'm in the process of creating a website for Rubik's cube scrambling and timing, and everything seems to be working well so far. I have implemented a scrambler, a timer, and a list of recorded times (still a work in progress). The timer is functi ...