React Credit Card Validator - JavaScript Exercise #10

React Credit Card Validator - JavaScript Exercise #10

Build a React Credit Card Validator using Luhn's Algorithm

Mar 7, 2023ยท

6 min read


In this exercise, you will build a React component that validates credit card numbers using Luhn's algorithm. The component will allow users to enter their credit card number and display whether the number is valid or not.

Luhn's Algorithm

Luhn's algorithm is a simple checksum formula used to validate credit card numbers, as well as other types of identification numbers. The algorithm is named after its inventor, Hans Peter Luhn, who developed it for IBM in the 1950s.

The algorithm works by starting at the rightmost digit of the credit card number and moving left. Each digit is multiplied by 2 if its position is even (counting from the rightmost digit as position 1), and multiplied by 1 if its position is odd. If the product of the multiplication is greater than 9, the two digits of the product are added together to produce a single digit.

Once all of the digits have been multiplied and added together, the sum is then divided by 10. If the remainder of this division is 0, then the credit card number is considered valid according to Luhn's algorithm.

Here's an example of how Luhn's algorithm works with a sample credit card number, 1234567890123456:

  1. Starting from the rightmost digit, the first digit is 6. This digit is multiplied by 2, because its position is even. The result is 12.

  2. The next digit to the left is 5. This digit is multiplied by 1, because its position is odd. The result is 5.

  3. The next digit to the left is 4. This digit is multiplied by 2, because its position is even. The result is 8.

  4. Continuing in this way, we get: 1+6+5+1+8+7+3+4+1+6+5+0+3+4+2+5 = 66

  5. Finally, we divide the sum by 10. 66 % 10 = 6. Since the remainder is not 0, this credit card number is not valid according to Luhn's algorithm.


  1. Create a new React component called CreditCardValidator.

  2. Add an input field where users can enter their credit card number.

  3. Add a button that will trigger the validation process when clicked.

  4. Implement Luhn's algorithm to validate the credit card number.

  5. Display a message indicating whether the credit card number is valid or not.

  6. Style the component to make it look like a credit card.

Bonus Requirements

  1. Add support for multiple credit card types (Visa, Mastercard, etc.).

  2. Display the credit card type based on the entered number.

Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.

So, grab a pen and paper, fire up your code editor, and get ready to dive into the React Credit Card Validator exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.

Output for the Credit Card Validator exercise

import React, { useState } from 'react';
import './CreditCardValidator.css';

const CreditCardValidator = () => {
  const [creditCardNumber, setCreditCardNumber] = useState('');
  const [isValid, setIsValid] = useState(null);
  const [cardType, setCardType] = useState('');

  const handleInputChange = (event) => {
    const input =\D/g, ''); // replace any non-numeric characters
    setIsValid(null); // reset validation status
    setCardType(getCardType(input)); // update card type

  const handleValidation = () => {
    const cardNumberWithoutSpaces = creditCardNumber.replace(/\s/g, '');
    const cardNumberLength = cardNumberWithoutSpaces.length;
    let sum = 0;

    if (cardNumberLength === 0) {

    for (let i = 0; i < cardNumberLength; i++) {
      let cardDigit = parseInt(cardNumberWithoutSpaces.charAt(i));
      if (i % 2 === 0) {
        cardDigit *= 2;
        if (cardDigit > 9) {
          cardDigit -= 9;
      sum += cardDigit;

    setIsValid(sum % 10 === 0);

  const getCardType = (cardNumber) => {
    const firstDigit = cardNumber.charAt(0);
    switch (firstDigit) {
      case '4':
        return 'Visa';
      case '5':
        return 'Mastercard';
      case '6':
        return 'Discover';
      case '3':
        const secondDigit = cardNumber.charAt(1);
        if (secondDigit === '4' || secondDigit === '7') {
          return 'American Express';
        if (secondDigit === '5') {
          return 'JCB';
        return 'Unknown';
        return 'Unknown';

  return (
    <div className="credit-card-container">
      <div className="credit-card-input-container">
          placeholder="Enter your credit card number"
        <button className="credit-card-button" onClick={handleValidation}>Validate</button>
      {isValid === false && <div className="credit-card-error">Invalid Credit Card</div>}
      {isValid === true && <div className="credit-card-success">Valid {cardType} Credit Card</div>}

export default CreditCardValidator;
.credit-card-container {
  display: flex;
  flex-direction: column;
  align-items: center;

.credit-card-input-container {
  display: flex;
  align-items: center;
  margin-bottom: 1rem;

.credit-card-input {
  font-size: 1.5rem;
  padding: 0.5rem;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 0.5rem;
  width: 20rem;

.credit-card-button {
  font-size: 1.5rem;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 0.5rem 1rem;
  cursor: pointer;

.credit-card-button:hover {
  background-color: #3e8e41;

.credit-card-error {
  color: red;
  font-size: 1.2rem;
  margin-top: 0.5rem;

.credit-card-success {
  color: green;
  font-size: 1.2rem;
  margin-top: 0.5rem;
import React from 'react';
import CreditCardValidator from './CreditCardValidator';
import './App.css';

function App() {
  return (
    <div className="App">
      <CreditCardValidator />

export default App;

Applications where the Credit Card Validator can be used

  1. E-commerce checkout page: In an e-commerce application, the CreditCardValidator component could be used to validate the user's credit card information before processing their order. This would help to prevent fraudulent transactions and improve the user experience by catching errors before they cause delays or complications.

  2. Membership registration form: A membership registration form could use the CreditCardValidator component to verify that the user's credit card is valid and in good standing before approving their membership. This could help to prevent membership fraud and ensure that the organization only admits legitimate members.

  3. Financial management application: A financial management application could use the CreditCardValidator component to validate credit card information when users add or edit their payment methods. This would help to ensure that the application has accurate and up-to-date payment information, and would also help to prevent errors or typos in the credit card numbers.

  4. Banking application: A banking application could use the CreditCardValidator component to validate credit card numbers when users add or update their payment methods. This would help to prevent fraudulent transactions and ensure that the bank has accurate and up-to-date payment information for its customers. Additionally, the component could be used to help users detect errors or typos in their credit card information, improving the overall user experience.

Please note that the examples and instructions given for using the CreditCardValidator component are intended for educational and exercise purposes only. This component should not be used for any malicious purposes such as phishing or fraudulent activity. It is important to always obtain user consent and follow ethical and legal guidelines when collecting, processing, or storing sensitive data such as credit card information.

When using the CreditCardValidator component in any application, it is the responsibility of the developer to ensure that they are following best practices for data security and user privacy and to comply with any relevant laws or regulations.

In this exercise, you learned how to implement Luhn's algorithm for credit card validation in a React component. You have also gained experience with handling form input, managing state, and displaying error messages.

Thanks for taking this JavaScript exercise!

I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practising and experimenting with React, and you'll be well on your way to becoming a skilled React developer!

If you have any questions or comments, feel free to reach out to me on Twitter(@rajeshtomjoe), or follow me for more updates.

And if you'd like to receive more exercise on JavaScript, be sure to subscribe to my blog.