Using regular expressions in JavaScript to permit a particular phone number pattern of (123) 456-7890 exclusively

I have implemented a phone number validation function for a web app. However, when this information is displayed in a windows app using a specific function that populates data to controls, it only accepts phone numbers in the format of (123) 456-7890.

(123) 456-7890

The current function allows users to enter any 10-digit phone number format, such as 123-45-6789.

function validatePhone(fld) {
    var error = "";
    var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');     

   if (fld.value == "") {
        return false;
    } else if (isNaN(parseInt(stripped))) {
        return false;
    } else if (!(stripped.length == 10)) {
        return false;
    } 
    return true;
}

I have researched online and found regular expressions for two formats (123) 456-7890 | 123-456-7890, such as (((\d{3}) ?)|(\d{3}-))?\d{3}-\d{4}. However, I need to restrict the validation to only one format with parentheses. Is there a way to modify this function to validate phone numbers in the exact format shown above? Thank you in advance.

Answer №1

Feel free to experiment with the regex pattern below:

const regexPattern = /^\(\d{3}\) \d{3}-\d{4}$/;
console.log(regexPattern.test("(123) 456-7890")); // true
console.log(regexPattern.test("123-456-7890")); // false

Answer №2

Check out the regular expression provided below to validate a phone number

const validNumber = "(123) 456-7890";
const invalidNumber = "1234567890";
const regEx = /^\(\d{3}\) \d{3}-\d{4}$/;
console.log(
  regEx.test(validNumber),
  regEx.test(invalidNumber)
);

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 design a webpage that adapts to different screen heights instead of widths?

I'm in the process of designing a basic webpage for a game that will be embedded using an iframe. The game and text should always adjust to fit the height of your screen, so when the window is small, only the game is displayed. The game will be e ...

Is it possible for using str_replace('<') to protect against code injected by users?

Recently, I've been working on a script that involves user input. In this script, I use echo str_replace('<', '&lt;', str_replace('&','&amp;',$_POST['input']));. It seemed like a solid f ...

Would it be expected for these two JQuery functions to exhibit identical behaviors?

If I have the following two JQuery functions - The first one is functional: $("#myLink_931").click(function () { $(".931").toggle(); }); The second one, however, does not work as expected: $("#myLink_931").click(function () { var class_name = $(thi ...

Transform a string into a property of a JSON object

One of my challenges involves extracting a value from a JSON object called Task, which contains various properties. Along with this, I have a string assigned to var customId = Custom_x005f_f3e0e66125c74ee785e8ec6965446416". My goal is to retrieve the value ...

Guide on exporting a dynamically imported class instance using ES6 modules in NodeJS

Currently, I am engrossed in a book on NodeJS that illustrates a simple web application example. In this example, the prerequisite is to have various data store classes housed in their respective modules and dynamically selecting the data store by configur ...

the `req.body` method fetches an object with a property named `json

Having an issue with accessing data from req.body in my form created with JS { 'object Object': '' } //when using JSON.stringify: { '{"A":"a","B":"b","C":"c"}': &apo ...

Ensuring the accuracy of a condition within an HTML form through the utilization of

I am interested in designing an HTML page that includes a small form. The form should include: Name Gender Date of Birth "I Agree" checkbox Submit button One important condition to note is that if the individual's age falls between 20 and 25 (calc ...

What is the best way to insert a permanent script tag into the body of a Gatsby site? Can conditional rendering be used to control

As an illustration: - const nation = "USA" import chat from './utils/script'; // script is imported from a file if(nation === "USA") // utilized conditionally in the component { chat } else { console.log("Not USA") } inform me witho ...

Struggles with arranging elements in the right position

Currently, I am in the process of learning CSS and working on developing a game that involves time and score. In short, here is what I aim to achieve: This is what I have so far: You can find my progress on jsFiddle: http://jsfiddle.net/yZKTE/ CSS: #b ...

What is the process for converting strings or text to EBCDIC using JavaScript?

In the midst of developing a website, I am working on a feature that allows users to input a minimum of 256 characters/strings (with code verification), choose between ASCII or EBCDIC conversion, and view the converted text string displayed on the page bas ...

Tips for integrating AsyncGenerators with Kotlin/JS

I am currently exploring the use of IPFS with Kotlin/JS, but my issue is not limited to that specific context. The functions ipfs.cat() and ipfs.get() return an AsyncGenerator, and I am uncertain about how to properly iterate over it using Kotlin (I am als ...

Images are failing to show up in the iPhone design

Encountering issues with displaying images on an iPhone? You can replicate the problem by minimizing your browser window horizontally. Here is a link showcasing the problem: here. To temporarily fix this, try zooming out the browser (Ctrl+-). You can see a ...

Using three.js inside Colab

Here are some examples showcasing bi-directional communications between Python and JavaScript in Google Colab: I'm trying to get this simple three.js demo to work in Colab. Any tips? Despite the seemingly straightforward source code, I'm facing ...

What is the best way to implement variable scope when using a callback function in AngularJS

I'm facing a major issue in my AngularJS application. I have a factory module with an getAll() function that retrieves JSON data from the server. In the controller module, I attempt to assign the value returned by the factory's getAll() function ...

Tips for setting up a material-ui theme on the go

How can the material-ui theme object be dynamically configured? This feature is activated by clicking on the "set docs colors" button located on the documentation page of mui. ...

Extract data from Markit On Demand API using JavaScript and AJAX

I'm struggling to properly parse the response from the API. While I can retrieve the entire response, I am a bit lost on how to effectively parse it. Below is my code snippet: <!DOCTYPE> <html> <head> <style> img ...

Incorporating JavaScript Object-Oriented Programming in PHP

As someone new to JS programming, I am tasked with developing a php web application that relies on ajax calls for all actions without reloading the page. While I have completed the php and JS code, I am struggling to understand what JS OOP entails. My coun ...

Is there a way to determine if two distinct selectors are targeting the same element on a webpage?

Consider the webpage shown below <div id="something"> <div id="selected"> </div> </div> Within playwright, I am using two selectors as follows.. selectorA = "#something >> div >> nth=1&q ...

Attempting to invoke setState on a Component before it has been mounted is not valid - tsx

I've searched through various threads regarding this issue, but none of them provided a solution that worked for me. Encountering the error: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a b ...

Personalized Angular dropdown menu

Recently, I've started delving into angularJS and I'm eager to create dropdowns and tabs using both bootstrap and angular. Although there is a comprehensive angular bootstrap library available, I prefer not to use it in order to gain a deeper und ...