Difficulties with validating phone numbers

I'm having an issue with my JavaScript code that is supposed to validate a phone number field, but it doesn't seem to be working. Even if I enter incorrect values, the form still submits. Here's the snippet of my code:

<script>
function validatePhone()
{ 
var num1 = document.getElementById('workno');

if (num1 !== null)
    {
    regex = /\(\d{2}\)\d{8}/;
    }
if (!num1.match(regex))
    {
    alert('That is not a correct telephone number format');
    return false;
    }
}
 </script>

<form name="eoiform" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validatePhone();">

<input type="text" id="workno" name="workno">

<input type="submit" name="submit" id="submit" value="submit">

</form>

Could someone help me pinpoint where I might have made a mistake?

Answer №1

The variable num1 contains an element object, not its actual value, so it cannot be tested with a regular expression in its current state.

If the element does not exist, num1 will be null; if it has no value, it will be "".

function validatePhone()
{ 
  var num1 = document.getElementById('workno').value;
  if (num1 !== "" && !num1.match(/\(\d{2}\)\d{8}/))
  {
    alert('The telephone number format is incorrect');
    return false;
  }
}

You also have an invalid form method="POST" in your HTML code.

Answer №2

How about choosing the data directly from the Input field? Give it a shot

if (!inputValue.value.match(pattern))

Answer №3

Aside from the issues mentioned in other responses, it's crucial to secure the regular expression by anchoring it. Failing to do so may permit additional characters before or after the phone number.

function verifyPhoneNumber()
{
  var phoneNumber = document.getElementById('phone').value;
  if (phoneNumber !== "" && !phoneNumber.match(/^\(\d{3}\)\d{7}$/))
  {
    alert('Invalid phone number format detected.');
    return false;
  }
}

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 align an image with the position of a div?

Looking for assistance on positioning an image to a div's position after it has been cloned. $(".raindrop1").clone().removeClass("raindrop1").appendTo("body"); $("img").css({"left": "div".x, "top": "div".y}); .shape{ border-radius: 50px; width: 10p ...

Limiting a text based on spaces or at the completion of a word within a string or sentence

Currently, I am utilizing a LimitTo filter to generate excerpts of article descriptions for display on the homepage of a website as snippets in the feature section. The LimitTo filter is set at a maximum of "100 characters," but it sometimes cuts off word ...

The website no longer uses AJAX calls and does not display any errors, although it used to do so in the past

I've noticed that my website is no longer making the ajax call it used to make before I made some changes to my code. However, I can't seem to figure out what exactly I changed. The function call appears to be correct as it triggers the initial a ...

Verify if the value in a textbox exceeds the number entered in an array of textboxes

My goal is to compare the value of a single text box, labeled as "totalmarkstoall", with multiple arrays of text boxes labeled as "marksscored". The JavaScript code below is set up to compare these values using a key up function. The issue I am facing is ...

Sending Node.js array from endpoint to Javascript function

I am facing an issue with my HTML chart that is supposed to display an array from a JavaScript function called 'window.testDataArray'. Instead of using a sample array, I want to fetch the array data from a server endpoint. However, I am unsure ab ...

What are some alternative ways to link a local MongoDB database to my Android Studio application instead of using MongoLab?

Can someone please help me figure out how to connect my Android Studio project to a MongoDB database stored locally on my PC? I've been searching for solutions that don't involve using MLab, but I haven't had any luck. I've attempted f ...

Please consider opening in a new tab rather than a new window

<a href='#' onclick="loadpage();">[RANDOM PAGE]</a> Whenever this code is clicked, the following function gets executed. function loadpage(){ $.ajax ({ type: "POST", url: "fetchpage.php", data: "showpage=1", success: function(msg) { ...

The proper way to link various asynchronous operations enclosed in promises

My current understanding of promises is that they serve as a wrapper for async functions within the outer environment (such as the browser or node.js). However, I am struggling with how to properly connect async operations using promises in software develo ...

Can someone please explain how to use the prevState in REACT?

Can you explain the difference between how to define the counterHandler function in these two examples? counterHandler = () => { this.setState(() => { return { times: this.state.times + 1 } }); } versus counterHandle ...

The functionality of the Ajax script seems to be optimized for Firefox browsers exclusively, as it is encountering issues with compatibility on other

My code works perfectly in Firefox, but I'm encountering an issue in all other browsers. Specifically, I'm getting the error message "SyntaxError: JSON Parse error: Unexpected EOF" on line if (this.readyState == 4 && this.status == 200). ...

Received an error while using an Express router: "Unable to access property 'caseSensitive' of undefined."

javaScriptCode app.js const express = require('express') const app = express() const {route} = require('./routes/route') app.use(express.static('./public')); app.use(express.json()); app.use(express.urlencoded()); app.use(rout ...

What is the best way to attach a jQuery UI event handler to a button that has been dynamically generated?

Currently, I have a jquery ui modal dialog box form that inserts items into a table. A specific column in the table contains a button which serves as a link to edit the particular row. My goal is to attach an event handler to this button so that when a use ...

Troubleshooting: Issue with Chrome's CSV Export Functionality in JavaScript/AngularJS

Currently, I am troubleshooting an issue with exporting a CSV file from a data table on a web application. The export functionality works fine on all browsers except for Chrome when the export button is clicked. I have been trying to solve this problem for ...

Guide to dynamically generating checkboxes or multi-select options in ASP.NET MVC 4

Within this project, we have implemented two separate lists - one for the dealer and another for their products. Currently, when selecting a specific dealer, all associated products are returned using JavaScript (Json). Utilizing Html 5: @using (Html.Be ...

Tips for applying multiple style properties to an element using JavaScript

I have been experimenting with different versions of this code in an attempt to modify a specific element for a coding challenge, but none of them seem to successfully change multiple styling properties of the element upon clicking on a button. Would great ...

The error message "POST .../wp-admin/admin-ajax.php net::ERR_CONNECTION_CLOSED" appears when a WordPress AJAX request receives data that exceeds 1MB in size

When I attempt to submit a jquery ajax form from the frontend and upload a blob (a variable of string) as a .txt file to WordPress using wp_handle_upload(), everything works smoothly until the file size reaches around 1mb. At that point, an error is displa ...

Implementing experimental decorators and type reconciliation in TypeScript - A step-by-step guide

My basic component includes the following code snippet: import * as React from 'react'; import { withRouter, RouteComponentProps } from 'react-router-dom'; export interface Props { }; @withRouter export default class Movies extends R ...

Stuffing a container with an image without considering the proportions

I am experimenting with filling a parent <div> with an image without concern for proportions. Despite knowing that it may not look great at all sizes, I just want to test its feasibility. Currently, the image is scaling instead of stretching to fit m ...

Having trouble with running `npm start` on a computer that has different versions of Node and

I have encountered an issue with running a React application on two different computers. One computer, a MacBook, is running the app without any problems, while the other, an Ubuntu 18.04 machine, is having trouble starting it. Here are the configurations ...

Exploring the World of Angularjs 2

Currently, I am diving into learning angularjs 2. I found a helpful git repository that I am following closely, which can be found here. The repository contains some interesting codes in the index.html file. <script src="node_modules/core-js/client/shi ...