The regular expression for validating credit card numbers is invalid due to a repetition error

Here is the regular expression I've been using to validate credit card numbers in JavaScript:

var match = /^(?:(4[0-9]{12}(?:[0-9]{3})?)|(5[1-5][0-9]{14})|?(6(?:011|5[0-9]{2})[0-9]{12})|(3[47][0-9]{13})|(3(?:0[0-5]|[68][0-9])?[0-9]{11})|((?:2131|1800|35[0-9]{3})[0-9]{11}))$/.exec(cardno);

Although this code was working fine before, it is now causing an error. Could someone please take a look at it and suggest any necessary changes?

Answer №1

One effective approach is to implement the LUHN test. Learn more about LUHN algorithm here

/*
validateCardNumber( cardNum )
   parameters:
      This function takes the card number as a text string and applies the Mod 10 formula to its digits.
   description:
      Mod 10 serves as the check digit formula for supported cards, aiming to validate them.
   returns:
      It returns true if the number passes the check digit verification.
      Otherwise, it returns false.
*/
function validateCardNumber( cardNum ) { // LUHN Formula used for credit card number validation
   var array = new Array( cardNum.length );
   var index = 0, totalSum = 0;

   for( index = 0; index < cardNum.length; ++index ) {
      array[index] = parseInt(cardNum.charAt(index));
   }
   
   for( index = array.length - 2; index >= 0; index-=2 ) { 
      array[index] *= 2;                      
      if( array[index] > 9 ) array[index]-=9;          
   }                               

   for( index = 0; index < array.length; ++index ) {
      totalSum += array[index];                   
   }

   return (((totalSum%10)==0)?true:false);       
}

Answer №2

Visit to input this code snippet: 14})|?(6(. The analyzer will advise removing the question mark since it implies the preceding token is optional, but it's actually followed by an or operator, not a token. Keep in mind that this distinction is crucial compared to using ?:, which signifies a non-capturing group.

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

Ways to substitute a single parameter within Vue.js router

We are working on a complex multi-level multi-tenant application, where the hostname is used to identify the 'supplier' account and the customer account is included in the URL structure. For example, our routes are structured like this: /:local ...

Component template using Knockout.js and RequireJS for HTML widgets

Trying to implement the widget example for knockout from here. Unfortunately, I am having issues loading the template from an external HTML file using requirejs. ko.components.register('like-or-dislike', { template: { require: &apos ...

Is combining form and fieldset causing issues?

My <form> for uploading an image and my <fieldset> for sending data via AJAX both work individually. However, when I try to merge them into one form, things get complicated. This is being done on a Node.JS server. Upload <form>: <for ...

Using two different Readable streams to pipe to the same Writable stream multiple times

In my current project, I am facing the challenge of concatenating a string and a Readable stream. The Readable stream is linked to a file that may contain data in multiple chunks, making it quite large. My objective is to combine these two entities into on ...

Using `ngRepeat` on a different array of values for repetition

Working with AngularJS. Here is an example of a JSON object: "skills": { "Charisma": {}, "Dexterity": { "Sk3": [ [ true, true, true, true, false ], 44 ] }, ... And the corresponding HTML: <div class="pan ...

What is the process for integrating custom fields into a product using Stripe, and how can a stock limit be implemented for each customized field?

Currently, as I develop an ecommerce website using Next.js and integrate Stripe for checkout, I've come across the feature of custom fields in Stripe. This feature allows me to add options such as small, medium, and large for clothing sizes. However, ...

What steps should I take to resolve the issue of my endpoint failing to accept POST requests?

I am in the process of developing a customized API, with an endpoint that is specified as shown below: https://i.stack.imgur.com/sZTI8.png To handle the functionality for this endpoint, I have set up a Profiling Controller. Inside my controller directory ...

Storing user input in MongoDB after encoding

I am currently exploring the most effective methods for storing and presenting user input in MongoDB. In traditional SQL databases, it is necessary to encode all user input as a precaution against injection attacks. However, in the context of MongoDB, ther ...

Preserve setTimeout() Functionality Across Page Refreshes and Navigations

I am trying to display an alert message after a 15-minute delay, but the functionality is disrupted when the page refreshes or if I navigate to a different page. This all takes place on a single web page. When a specific button is clicked, it should trig ...

`Switching between two buttons: A guide`

Here is the codepin: https://jsfiddle.net/magicschoolbusdropout/dwbmo3aj/18/ I currently have a functionality in my code that allows me to toggle between two buttons. When I click on one button, content opens and then closes when clicked again. The same b ...

The jQuery ajax function seems to be malfunctioning when attempting to send a post request

Having trouble with AJAX? Let me show you my approach to making a POST request to my RESTful service using AJAX: var lat = marker.getPosition().lat(); var lng = marker.getPosition().lng(); //xmlhttp.open("GET","http://192.168.1.100:8080/MapDemo/serv ...

Skipping a JSON field in HTML/JavaScript when it is blank: A guide for developers

To develop an interactive program based on JSON input, I aim to display headers, subheaders, and choices derived from the JSON data. Some input fields may remain unfilled. For instance: Header Subheader Choice 1 Choice 2 Subheader2 Choice ...

Sending data from the server to the client in MVC using C#

I sent a token from a View to a function in my HomeController, and now I need to process the token and send back the information to the frontend. I assumed that the resultData returned by the ajax call would be the output of GetMyData, but it turns out it& ...

Is it possible to change the text of a scrollspy dropdown to a default text when it is not actively tracking any items?

I am new to Vue and currently implementing Bootstrap Vue Scrollspy (view example here). My sticky dropdown is tracking all referenced content and updates with the current section in view. You can check out my code sample here. Is there a way to set the d ...

I am experiencing issues with the middleware not functioning properly after implementing a custom application with Next.js

I'm currently diving into Next.js version 13 and attempting to customize the app based on the standard documentation. However, it seems that the middleware isn't being invoked as expected. I suspect there might be something wrong with my implemen ...

Operate on Nested JSON Arrays

I have the following JSON array: var salesData = [ { "products": "Cars", "solddate" : "2022-01-01", "noofitems" : " ...

Having trouble with Vue 3 Component State not updating following an asynchronous operation?

Encountering challenges in my Vue 3 app when trying to update a component's state post an asynchronous operation. Here's what's happening: Within a component, there is a method called containerMoveHere that utilizes Socket.io for an async o ...

Triggering createEffect in SolidJS with an external dependency: A guide

Is there a way to use an external dependency to trigger the createEffect function in Solid, similar to React's useEffect dependency array? I am trying to execute setShowMenu when there is a change in location.pathname. const location = useLocation() ...

update the element that acts as the divider in a web address (Angular)

Is it possible to modify the separator character used when obtaining the URL parameters with route.queryParams.subscribe? Currently, Object.keys(params) separates the parameters using "&" as the separator. Is there a way to change this to use a differe ...

The operation failed because the property 'dasherize' is inaccessible on an undefined object

While attempting to execute the following command: ng generate component <component-name> An error occurred saying: Error: Cannot read property 'dasherize' of undefined Cannot read property 'dasherize' of undefined The confi ...