Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript regex - Validate Credit Card in JS
Next article icon

JavaScript regex - Validate Credit Card in JS

Last Updated : 19 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To validate a credit card number in JavaScript we will use regular expression combined with Luhn's algorithm. Appling Luhn's algorithm to perform a checksum validation for added security

Luhn algorithm:

  • It first sanitizes the input by removing any non-digit characters (e.g., spaces).
  • It then processes the digits from the end, doubling every second digit, and subtracting 9 if the doubled value is greater than 9.
  • The sum of all digits is calculated, and if the sum is divisible by 10, the card is valid.
JavaScript
function validCard(n) {     // Remove all non-num characters (e.g., spaces or hyphens)     const s = n.replace(/[^0-9]/g, '');      // Check if the input length is valid (most cards have between 13 and 19 nums)     if (s.length < 13 || s.length > 19) {         return false;     }      let sum = 0;     let sd = false;      // Loop through the card number nums, starting from the last num     for (let i = s.length - 1; i >= 0; i--) {         let num = parseInt(s[i], 10);          if (sd) {             num *= 2;             if (num > 9) {                 num -= 9; // If the result is a two-num number, subtract 9             }         }          sum += num;         sd = !sd; // Toggle the doubling     }      // If the total sum is divisible by 10, it's a valid card number     return sum % 10 === 0; }  const n = '4539 1488 0343 6467'; // Example Visa number if (validCard(n)) {     console.log('Valid credit card number.'); } else {     console.log('Invalid credit card number.'); } 

Output
Valid credit card number. 

Luhn algorithm validates only the format. But How to check on the card was from which company.

Determining the Credit Card Issuer

JavaScript
function getIssuer(num) {     // Remove all non-digit characters (e.g., spaces or hyphens)     const s = num.replace(/[^0-9]/g, '');      // Check the length of the card number     if (s.length < 13 || s.length > 19) {         return 'Invalid card length';     }      // Determine the card issuer     if (/^4/.test(s)) {         return 'Visa';     } else if (/^5[1-5]/.test(s)) {         return 'MasterCard';     } else if (/^3[47]/.test(s)) {         return 'American Express';     } else if (/^6(?:011|5)/.test(s)) {         return 'Discover';     } else if (/^3(?:0[0-5]|[68])/.test(s)) {         return 'Diners Club';     } else if (/^35/.test(s)) {         return 'JCB';     } else {         return 'Unknown issuer';     } }  const num = '4111 1111 1111 1111'; console.log(`The card issuer is: ${getIssuer(num)}`); 

Output
The card issuer is: Visa 

Explanation credit card issuer:

  • Visa cards start with the digit 4.
  • Master Card cards typically start with numbers ranging from 51 to 55.
  • American Express (Amex) cards start with 34 or 37.
  • Discover cards may start with 6011 or have other prefixes starting with 65.
  • Diners Club cards can start with specific ranges such as 300-305, 36, or 38.
  • JCB cards often start with 35.

Next Article
JavaScript regex - Validate Credit Card in JS

G

geekcoder2298
Improve
Article Tags :
  • Project
  • JavaScript
  • Web Technologies
  • Dev Scripter
  • JavaScript-Projects
  • Dev Scripter 2024

Similar Reads

    JavaScript - Validate URL in JS
    We will explore different approaches to validating URLs in JavaScript. These approaches include using regular expressions (regex), the URL constructor, and various npm packages. let's see one by one.All valid URLs follow a particular pattern. They have three main parts, which are: ProtocolDomain nam
    2 min read
    How to Validate Email Address using RegExp in JavaScript?
    Validating an email address in JavaScript is essential for ensuring that users input a correctly formatted email. Regular expressions (RegExp) provide an effective and efficient way to check the email format.Why Validate Email Addresses?Validating email addresses is important for a number of reasons
    3 min read
    Credit Card Number Validator using ReactJS
    Credit card validation is an important step in every application in order to authenticate the user's credit card number so that the application can proceed to the payment process if needed. It can be achieved using the validator module in ReactJS. The following example shows how to validate the user
    2 min read
    How to Validate String Date Format in JavaScript ?
    Validating string date format in JavaScript involves verifying if a given string conforms to a specific date format, such as YYYY-MM-DD or MM/DD/YYYY. This ensures the string represents a valid date before further processing or manipulation. There are many ways by which we can validate whether the D
    5 min read
    How to Validate Decimal Numbers in JavaScript ?
    Validating user input is an essential aspect of Web Development. As a developer, when we are playing with the numeric inputs provided by the end-user, it is quite important to ensure that the input provided by the user is in the correct format. We can use the regular expression to Validate Decimal N
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences