Validating Credit Card Numbers with Spaces

Currently, I am in the process of creating a credit card form that requires validation using checkValidity to match the specific card pattern that is dynamically added to the input field.

For example, if a user enters a Mastercard number such as 5454545454545454, it will be formatted with spaces like this: 5454 5454 5454 5454. Subsequently, I change the pattern attribute for that field to the Mastercard regex - ^(?:5[1-5][0-9]{14})$. However, when triggering checkValidity on input blur, it returns false when it shouldn't. I suspect this issue stems from the formatting causing the pattern to fail.

My dilemma lies in finding a solution to validate patterns with spaces for the given regex, perhaps by removing spaces during validation or adjusting the regex to include spaces. Alternatively, I am open to exploring other solutions to address this challenge effectively.

Answer №1

If you want to accomplish this task easily, jQuery can be a helpful tool. You may have a scenario where the credit card number is loaded dynamically or entered by the user, and then you need to validate it after adding spaces.

To remove any white spaces from the credit card number, you can utilize the .replace() function in JavaScript. This will allow you to send the formatted number for validation without any issues.

For more information on how to use the .replace() method, check out the documentation here.

Below is a quick example I've put together for demonstration purposes. Run the snippet to see it in action:

//Example of dynamically adding a card number
var ccNumber = '1234567890123456';
var addSpaces = ccNumber.match(/.{1,4}/g);
$('#credit-card').val(addSpaces.join(' '));

//Removing white spaces from the entered card number
var getCardNumber = $('#credit-card').val()
var NoSpacesCCNumber = getCardNumber.replace(/\s+/g, '')
console.log('Validated card number without spaces = ' + NoSpacesCCNumber)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="label" for="credit-card">Credit card</label>
<input id="credit-card" value="" autocomplete="off" type="text" />

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

Updating a particular element within nested arrays: best practices

I have developed a data table containing student records using material UI. Each row represents a different student array with a fee verification button. My goal is to change the fee status when the button is clicked for a specific student, but currently t ...

"The file upload function is populating the req.body object, but not the req.file

I successfully implemented a file upload API using multer and express, which functions well when accessed through POSTMAN. However, I encountered an issue when trying to utilize the same API with another file upload API: The code I used can be found below ...

Vue alert - Cannot access indexOf property of a value that is undefined

After browsing through numerous similar issues on StackOverflow, none seem to address the specific problem I encountered... I have been smoothly working on a Vue JS project + Laravel until I suddenly encountered an error that seems unsolvable (even though ...

Expanding the capabilities of search and replace in Javascript is imperative for enhancing its

I have developed a search and replace function. How can I enhance it by adding a comment or alert to describe the pattern and incorporating a functional input box? Any suggestions are welcome! <html> <head> <title> Search & Replace ...

The getStaticProps() method in NextJS does not get invoked when there is a change in

I have integrated my front-end web app with Contentful CMS to retrieve information about various products. As part of my directory setup, the specific configuration is located at /pages/[category]/items/[id]. Within the /pages/[category] directory, you w ...

Click here to open in a new tab and experience the ever-changing dynamic

Imagine a scenario where a property site displays the main viewed property ad at the top, with smaller ads in square divs below. When a user clicks on one of the smaller ads, it dynamically swaps places with the main ad thanks to JavaScript. All ad data is ...

Tips for creating a substitute for a standard prototype in JavaScript

Having trouble with a JavaScript interpreter that has a buggy Array.prototype.sort. I want to replace it, at least for testing purposes. I have a function called mySort(array, comparator), but how can I make it work like array.sort(comparator)? I also ne ...

How to achieve padding of strings in JavaScript or jQuery

Does anyone have information on a similar function in jQuery or JavaScript that mimics the prototype toPaddedString method? ...

Capturing errors during function declaration in JavaScript

A problem has arisen in the below function definition due to a script error function foo () { try { var bar = function() { ERROR } } catch (exception) { console.debug("exception"); } } foo(); However, th ...

What is the process of creating a for loop in FindById and then sending a response with Mongoose?

Is there a way to get all the data in one go after the for loop is completed and store it in the database? The code currently receives user object id values through req.body. If the server receives 3 id values, it should respond with 3 sets of data to th ...

Is it possible to overlay color on top of a div background? (i.e. modify div color without altering the 'background-color' property)

Can you apply a color "on top of" a div's background? I'm looking to change the displayed color of a div without altering the 'background-color' value. I need to keep the background-color for comparison when divs are clicked: var pick ...

Is it possible to execute in a specific context using npm?

I am seeking to execute npm scripts that are executable by VuePress. For instance, I have VuePress installed and would like to run the command vuepress eject. Although I can access vuepress in my scripts, there is no specific script for eject: "scr ...

Save information in a nested object within local storage by utilizing a dynamic key

Storing the below object in localStorage to simulate server-side login/logout functionalities. Current user logic is implemented to identify the logged-in user. let defaultUsers = [ { email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Determine the initial left position of a div element in CSS prior to applying

Scenario : const display = document.querySelector('.display'); const container = document.querySelector('.outer-div'); document.addEventListener("click", (event) => { if (!event.target.closest("button")) return; if(event ...

How do I utilize jQuery to retrieve initials from the name field of a form?

I'm on the hunt for a clever solution to a rather ugly problem. I have a form that accepts a full name as input and passes it to a function. Now, I need to transform that full name into its initials (e.g. 'John Doe' becomes 'JD') b ...

underscore.js provides _.where utility for filtering arrays of strings and objects

I am looking to verify whether a specific string is present in a collection of objects. The variable this.props.value contains the string "apple, peach" and this.state.list consists of a list of objects with key-value pairs. My goal is to determine if "ap ...

How can we prevent components from rendering in React when their state or props have not changed?

I encountered a problem in my project where I have a main component that serves as the parent component of my project. Inside this main component, I have defined routes for other components and directly imported some components like a Side Navbar and Login ...

Using the Ngclass function with a pair of objects

Can you include 2 objects in an ngclass function like this? <div class="progress-bar"[ngClass]="getProgressValues(obj.val1,obj.val2)"> </div> I am encountering a JSON error. SyntaxError: JSON.parse: bad control character in string literal at l ...

Steps to define a JavaScript mixin in VueJS

Currently, I am working on a Vue project with TypeScript and in need of using a mixin from a third-party library written in JavaScript. How can I create a .d.ts file to help TypeScript recognize the functions defined in the mixin? I have attempted the fol ...

What methods are available to transfer a variable from one component to another in React?

In my React app, I have a form component that interacts with a PostgreSQL database to send data. Here is the script for my form: import bodyParser from 'body-parser'; import React, { Fragment, useState } from 'react'; import RatingStar ...