JSLint indicates a syntax error with the message "missing : and found ')' instead" related to a regular expression

function validatePhoneNumber(input) {
    var phoneNumberRegex = /^(?([0-9]{3})\)?[-.]?([0-9]{3})[-.]?([0-9]{4})$/;
    if (input.value.match(phoneNumberRegex)) {
        alert("Valid Phone Number");
        return true;
    } else {
        alert("Not a valid Phone Number");
        return false;
    }
}

I encountered an error when using jslint to validate the above code:

https://i.sstatic.net/wZz5E.png

Can anyone help me identify what is causing this issue?

Answer №1

It seems like the solution to your issue lies in escaping those dashes within your regex pattern. However, there may still be some additional adjustments needed before your code passes all linting tests.

Despite that, the provided code is successfully passing linting checks, and the regex validation remains effective when tested on regex101.com (credit goes to torazburo).

/*jslint browser:true */
/*global window */
function phoneNumberValidation(inputText) {
    "use strict";
    var phoneNumberPattern = /[0-9]{3}?[\-.]?[0-9]{3}[\-.]?[0-9]{4}$/;
    if (inputText.value.match(phoneNumberPattern)) {
        window.alert("Valid Phone Number");
        return true;
    }

    // Previously, JSLint would flag "Unnecessary 'else' after disruption.",
    // however, it appears this is no longer a mandatory rule.
    window.alert("Not a valid Phone Number");
    return false;
}

This raises another inquiry, as highlighted by @torazaburo: How can one validate a phone number in JavaScript?. There are several insightful responses on StackOverflow addressing this query.

Personally, I find this approach quite appealing, even though I haven't personally utilized the library it recommends. Notably, this library is developed by Google and undergoes frequent updates, indicating its reliability over hastily constructed alternatives. Best of luck with your implementation.

Answer №2

There are actually two mistakes in your code. The first parenthesis in the regular expression needs to be escaped, and there is an illegal semicolon in the if statement. Here is the corrected version of the function:

function phoneValidation(inputtext) {
  var phoneNumber = /^\(?([0-9]{3})\)?[-.]?([0-9]{3})[-.]?([0-9]{4})$/ 
  if (inputtext.value.match(phoneNumber)) {
    alert("Valid Phone Number");
    return true;
  } else {
    alert("Not a valid Phone Number");
    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

Giant Slide - navigate directly to a particular slide using a link

Hey there, I am currently working on incorporating the Superslide slider for fullscreen images in my website. My goal is to have a mostly text-free site where users can navigate through the images using the main menu or jump to a specific image within the ...

Retrieving data from handlebars variable in a client-side JavaScript file

When creating a handlebars view using hbs for the express js framework, I am faced with an issue of accessing the variables passed to the view from a separate JavaScript file. Here's an example: var foo = {{user.name}} This code obviously results ...

Is there a way to programmatically update the content of a React Bootstrap modal?

I have been attempting to modify the content of a modal after it has been loaded, but I am struggling to identify the correct nodes for modification. I have added references to the nodes I want to change and attempted to alter them in componentDidMount(). ...

Ways to conceal all components except for specific ones within a container using JQuery

My HTML structure is as follows: <div class="fieldset-wrapper"> <div data-index="one">...</div> <div data-index="two">...</div> <div data-index="three">...</div> < ...

javascript utilize jquery to advance saved event

When it comes to hyperlinks, I am pausing some of my native click events to verify if the resulting page contains the desired content. After storing the jquery event object and performing some validations, my goal is to allow the event to continue as usua ...

Converting HTML into an object using $compile

I am currently working on calling an HTML template and want to bind the data with Angular. I successfully retrieve the data to bind and the HTML, but when I try to compile it, it returns all the HTML binded as an object. How can I convert it back to plain ...

Manipulating variables in the main controller scope from a function in a transcluded directive scope using AngularJS

How can parent controller scope variables be updated from a transcluded directive scope's function? I have a situation where I am including directives within another directive using transclusion. Here is an example of how it is set up: <my-table& ...

Transforming a PHP cURL call to node.js

Currently exploring the possibility of utilizing the Smmry API, however, it seems that they only provide PHP API connection examples. Is there anyone who could assist me in adapting it into a JS request? My requirement is simple - I just need it to analyz ...

In Java, what is the significance of "1" within this particular string?

System.out.println("\1"); I was under the impression that it wouldn't compile due to the escape sequence not being recognized. Can you clarify what "\1" is supposed to represent? ...

What causes setInterval to create an endless loop when used inside a while loop in JavaScript?

I attempted to initiate a delayed "one" call or a "one or two?" question, but instead of working as expected, the function continued running indefinitely. Surprisingly, everything worked perfectly fine without using setInterval. quester2() function quest ...

Steps to bring life to your JavaScript counter animation

I need to slow down the counting of values in JavaScript from 0 to 100, so that it takes 3 seconds instead of happening instantly. Can anyone help me with this? <span><span id="counter"> </span> of 100 files</span> <s ...

AngularJS unit testing with $httpBackend is impacted by conflicts with UI-Router

Here is a controller that utilizes a submit function: $scope.submit = function(){ $http.post('/api/project', $scope.project) .success(function(data, status){ $modalInstance.dismiss(true); }) .error(function(data){ ...

Verification of data using PHP, MySQL, and jQuery

I'm currently working on a process to extract data from an Excel file and then pass it on to a PHP file for validation against a database. If the data doesn't exist in the database, a message will be displayed to notify the user of incorrect data ...

The data insertion query in MYSQL seems to be malfunctioning

I am facing an issue with inserting data from a form into a database table named "sumation". Despite using PhpStorm IDE, I am getting errors indicating that no data sources are configured to run the SQL and the SQL dialect is not set up. Can anyone help ...

Vue function displays 'undefined' message

Although many posts on this topic exist already, I am struggling to understand what is going wrong (even after searching extensively here and on Google). I have created my interceptor like this, but I keep receiving an error message stating "This is undef ...

How can you enable fullscreen for a featherlight iFrame?

I have implemented Featherlight to display an iframe within a popup modal on my website. If you click the iframe button, you can see a demo of how it works. One issue I am facing is that the generated iframe tag by Featherlight does not include allowfulls ...

I need assistance with a feature on my website where a new form is added every time the invite button is clicked, and the form is deleted when the delete button is

Invite.js This invite component includes an invite button outside the form and a delete button inside the form. The goal is to delete the form when the delete button is clicked. I have utilized useState and sourced this form from material-ui. Can anyone ...

Tips for updating multiple fields in Prisma ORM

Is there a way to upsert multiple fields in Prisma ORM using just one query? I'm looking for a solution that allows me to upsert all fields at once, without having to do it individually. Is this possible? ...

How to correctly serialize nested maps in JQuery ajax data for sending?

var locationData = { "location" : { "name" : $("#user_loc_name").val(), "street_address" : $("#user_loc_street_address").val(), "city" : $("#user_loc_city").val(), "province" : ...

Custom Component in React Bootstrap with Overflowing Column

I am working on a custom toggle dropdown feature in my React application: import React from 'react'; import 'react-datepicker/dist/react-datepicker.css'; const DateRange = props => ( <div className="dropdown artesianDropdo ...