A JavaScript code snippet to format a phone number in the pattern xx-xxxxxx

Please help me create a JavaScript function that can determine if the text in a textbox is a number. If it's not a number, I would like the function to focus on the textbox and change the format to look like this (xx-xxxxxx) when numbers are typed in, such as (12-123456). I am new to JavaScript and could use some guidance.

Here is what I have so far:

function checkNumber(elem)
{
    if(Number.isInteger(elem))
    {
        // To validate the format(xx-xxxxxx)
    }
    else
    {
        elem.focus();
    }
}

Answer №1

Make use of the following Regular Expression

^\d{2}-\d{8}$

Example of Valid format: 22-22229999

In this case, 2 and 8 represent the number of digits required. You have the flexibility to adjust it based on your needs.

function CheckValidity(contact)
{
 var pattern = "^\d{2}-\d{8}$";
 return pattern.test(contact);
}

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

Take the user input from the form and incorporate it into the URL for the AJAX request

How can I dynamically update the URL in the AJAX call asynchronously? I've made a few attempts, but none of them seem to work. This is the current code: <!-- Input form --> <form class="navbar-form navbar-left" role="search" id="formversion" ...

Tips for Implementing a Footer Component in ReactJS

My current setup includes: https://i.stack.imgur.com/2gvHk.png A navigation bar Nested content with a wizard and partial windows. A dynamic footer whose buttons and functionality need to change based on certain scenarios in the content. Currently, I ha ...

Is there a way for me to access the response from the PHP file I'm calling with Ajax?

I am just starting to explore ajax and jquery, and I recently found a code online that I'm tweaking for my own use. However, I am struggling with how to handle responses from PHP in this context. The current setup involves ajax POSTing to a php page ...

Load CSS stylesheet depending on Internet Explorer document mode

As I work on my website, I am facing the challenge of incorporating different versions of my style sheet based on the browser's document mode, not the browser mode. For instance, if the documentmode = ie8, I may need to load main_ie8.css, whereas for ...

Modifying the content in one form field based on the information entered in another input field

I have a scheduling application that includes a form for selecting both the departure city and arrival city. The app is designed for international travel only, so when a user selects a city from Hungary as the departure city, I want to exclude all Hungaria ...

Changing over to the left hand coordinate systemUniquely converting to a

One of the challenges I am facing involves an application that loads a model. Upon receiving a server response, I am provided with information regarding the axis to use for the right and up orientation. The format in which this information is sent can be ...

What is the best way to cut and combine multiple array elements in the right positions?

let result = response.data; console.log(result); const newTemp = result.ssps_with_scated.splice(5,1).concat(result.ps_with_ed.splice(2,1))[0]; result.ps_with_ed.push(newTemp); After multiple attempts, I finally achieved my goal. However, the array values ...

Converting Ajax to JSON with Jquery offline and Manifest for enhanced offline web applications

Looking to create an offline web application, I'm in the process of transitioning from Ajax to JSON using JQuery offline. Here is the initial Ajax code: $.ajax({ url: contentpage, data: contentpagedata, cache: false }).done(function( html ) { ...

How can MVC and WEB API work in tandem with the same controller?

Below is the code for my Controller: namespace MvcApplication.Controllers { public class HomeController : Controller { public ActionResult Contact() { ViewBag.Message = "Your contact page."; retu ...

JavaScript: Repeated Depth First Exploration for hierarchical rearrangement implemented with d3's recursion()

I'm attempting to perform a depth-first search on a complex JSON object, such as the one available through this link. My goal is to generate a modified object structure that looks like this: [ { name: "Original Object", children : [ ...

When incorporating script tags in React, an "Unexpected token" error may arise

I am in the process of converting my website to a React site, but I am encountering an issue with the script tags not working. It keeps showing an unexpected token error. Here is the code snippet: <div className="people"> How many people are you ...

I'm having trouble getting jquery css to function properly in my situation

I am trying to implement a fallback for the use of calc() in my CSS using jQuery CSS: width: calc(100% - 90px); However, when I tried running the code below, it seems like the second css() function is not executing. I suspect that there might be an issu ...

Signing off from GitHub Packages for npm

As I work on a project that utilizes a private GitHub package, I have been using it locally with the command npm login --registry=https://npm.pkg.github.com. However, this approach has posed problems when attempting to deploy the project in a production en ...

Guide on incorporating typed components into module federation in React

I've been encountering an issue with setting the type of a custom component exposed through Webpack module federation. Though I have successfully exposed and used the component, Typescript is flagging an error regarding its type. The situation invol ...

Facing a challenge with displaying an angularjs template within a popover

I am having trouble displaying custom HTML content in a popover when clicking on my "View" link. Although other content is rendering correctly, such as one with an ng-repeat inside it, my custom directive does not seem to be processed and displayed properl ...

Automated tools and frameworks for the testing of website performance

Hello, I have a website that heavily relies on AJAX for server communication. I am looking to conduct performance and stress testing using automated scripts. Can you provide any suggestions or recommendations? I am specifically interested in the functiona ...

Reload a jquery pop up upon closing a pop up window

I have a modal pop up that appears after clicking an ASP button : <div class="form-group"> <asp:Button ID="btnBrand" runat="server" Text="Add brand" CssClass="btn btn-info" OnClick="btnAdd_Click" /> </div> Code Behind : protected ...

What is the purpose of sorting an object using the sequence defined in an array?

Have you ever wondered how the sortWeekFunction function can rearrange an object based on a predefined array order? It may seem complex at first glance, but let's break down how this code actually works. const weeksArr = ['sunday', ' ...

Is it possible to execute a specified quantity of Promises simultaneously in Nodejs?

Currently, I am working on developing a web scraping application that utilizes a REST API to gather information from multiple entities on the server. The core functionality of this application can be summarized as follows: let buffer = [] for(entity in ent ...

removing a property from an object using AngularJS

Currently, I am working on a project involving AngularJS. The main goal of this project is to create a dynamic JSON generator using AngularJS. I have already developed the initial version and it works well. However, there is a minor issue with my applicati ...