Javascript phone number verification- eliminating error messages

Objective:

To ensure that phone numbers are entered in the correct format (e.g. 208-111-1111) and display an error message if the format is incorrect. How can we make sure the error message disappears once the user re-enters the correct format?

JS
phoneNumber = document.getElementById("phone");

var result = phoneNumber.toString().match(/^\d{3}-\d{3}-\d{4}$/);

function validatePhone(){
if (result == null)
{
error2.innerHTML = "The number is not in a correct format";
} else 
{
error2.innerHTML = " ";
};
}

HTML
<p>Phone:</p> 
      <input type = "text" id="phone" name="phone" onChange="validatePhone()">
      <br>
      <span id="error2" ></span>

Answer №1

function checkPhoneNumber() {
  phoneNumber = document.getElementById("phone");
  var result = phoneNumber.value.match(/^(\d{3}-\d{3}-\d{4})?$/);
  if (result == null) {
    error2.innerHTML = "Invalid phone number format";
  } else {
    error2.innerHTML = "";
  };
}
<p>Phone Number:</p>
<input type="text" id="phone" name="phone" oninput="checkPhoneNumber()">
<br>
<span id="error2"></span>

Answer №2

An issue arises when using the phoneNumber.toString() method.

The function of toString() on a DOM input element does not fetch the user input value. Its purpose is to generate a string representation of the object it operates on, rather than fetching a stored value from the object.

To obtain the desired value, use phoneNumber.value instead.

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

Combining server-side and client-side routing in AngularJS: A comprehensive guide

Currently, I am in the process of transitioning a project to an Angular-based Single Page Application (SPA). The project is originally built using node/locomotivejs and serves templates from the server side. Due to its large size, we are converting it to A ...

Is your custom shader material experiencing a lengthy initialization process?

After spending more than a year working on a raymarched project in three.js, I've noticed that as the complexity of the project has increased, so has the initialization time. It now takes over 40 seconds to load the project in the browser, but once lo ...

Repeater in ASP controls the unique identification generation process

When designing my page, I encountered an issue with automatically generated IDs within the repeater item template. Let me explain: <asp:Repeater ID="rptThreads" runat="server" onitemcreated="rptThreads_ItemCreated"> <HeaderTemplate> ...

The 'ReactType' type is not generic within material-ui@next

After installing material ui@next, I encountered an error in the node modules. ERROR in [at-loader] ./node_modules/material-ui/Avatar/Avatar.d.ts:8:15 11:31:52 web.1 | TS2315: Type 'ReactType' is not generic. 11:31:52 web.1 | ERROR in ...

What causes useEffect to be triggered multiple times, even when it is dependent on another useEffect function that is being executed repeatedly?

I have a specific requirement that involves using two useEffect hooks. First useEffect is used to set the latitude and longitude in the state with an empty dependency array. useEffect(() => { navigator.geolocation.getCurrentPosition(geo = ...

Set a class for the element created with document.createElement('img') method

Is there a way to apply the .rotatable class to the image below without using ('src', 'rotate.png')? $(document.createElement('img')).attr('src', 'rotate.png') css: .rotatable { cursor: move; bac ...

Tips on appending a parameter to an image URL using JavaScript

On my website, I am able to insert images with specified width and height using this code: <img src="image.php?w=100&h=100"> I would like the image size to change based on the device screen width. For screens smaller than 600px, I want to displa ...

Utilizing only JavaScript to parse JSON data

I couldn't find a similar question that was detailed enough. Currently, I have an ajax call that accesses a php page and receives the response: echo json_encode($cUrl_c->temp_results); This response looks something like this: {"key":"value", "k ...

Where should JSON data be sourced from when developing a service in AngularJS?

Just starting out with Angular! Am I correct in assuming that when creating a service, you request JSON data from a server controlled by someone else? For example, if I wanted to develop a Weather app, where could I find the JSON data? Is there a standar ...

When the Button is clicked, the component utilizing the Router fails to appear

My current task involves creating a page where users can choose between two options: Button 1 leads to TestOption.js, while Button 2 redirects to TestOption2 (currently using TestOption for testing purposes). The default landing page is SelectionPage. The ...

What is the simplest way to run a basic express js script?

I am encountering an issue while trying to run a basic express script in JavaScript. Every time I attempt to execute the script, I keep getting an error message stating that "require is not defined". Below are snippets of the code. Thank you! const expres ...

What is the method for incorporating a counter variable into a variable's name?

Here's my code, which I know is very inefficient: var slider1 = new Slider("#survey1", { precision: 2, value: 5 }) var slider2 = new Slider("#survey2", { precision: 2, value: 5 }) var slider3 = new Slider("#survey3", { precision: ...

Connecting actions and reducers through promises in React

My current approach involves making two http requests to an API in order to retrieve data. getServerDetails(this.props.match.params.id) //1 .then(res => { this.props.getServerDetailsAction({ success: true, data: res.data }) ...

How can I use express.js to run a function upon receiving an HTTP request?

I am facing a situation where my angular controller triggers an http request upon clicking a button. My node.js server receives this request and responds with YOU HAVE SUCCEEDED! HTTP REQUEST RECEIVED!. The challenge I'm encountering is that the funct ...

Fill in the text boxes using an AJAX request

I am currently working on an MVC project that involves filling out forms with user information. Each recorded entry is given a unique Id that is associated with all the details submitted in the form. My next task is to create a page for editing these form ...

Use Entity Objects instead of Strings in your Ajax requests for improved data handling

As I work on developing a web portal with Freemarker(FTL) as the front end technology, my project revolves around a single FTL page that utilizes a wizard to manage various user requests. The back end is structured using the Spring MVC pattern, where contr ...

Is there a way to maintain the selected position on the drop-down menu for users?

Whenever I choose an option from the drop-down field in my form, it automatically jumps back to the top of the page. Just to clarify, I have a drop-down menu at the top of the page and several input fields below. Users need to scroll down to reach the dro ...

AngularJS and numerous parallel indexed tables side by side

I need help with displaying two tables, one for profiles and the other for rates. The rates are connected to profiles through the rate name in the JSON data. Is there a way to show these two tables side by side? And when a row is selected in the profile ta ...

Introduce a timeout in the ajax request

I'm currently facing an issue with adding a 2-second delay between the loader icon and the success message displaying the data as html. I attempted to use setTimeout in my ajax code with a specified delay number, but it doesn't seem to be workin ...

Adding a cell break line within AG-GRID in an Angular application

I'm trying to display two sets of data in a single cell with ag-grid, but I want the data to be on separate lines like this instead: Data with break line I attempted to use "\n", "\r", and "\br" but it didn't work. Here is my code ...