How to validate a credit card number in ReactJS?


When a bank issue any credit or debit card number, they don’t generate the random numbers for the card. They follow some rules to issue a new card number. They first validate the card number using the Luhn algorithm and check if it starts with a particular number.

Here, we will learn different approaches to validating credit card numbers.

Use the React Creditcard Validator NPM Package

The react creditcard validator is an NPM package, allowing us to validate the card number. Whenever a user enters the credit card number, It checks which type of card it is. For example, it shows the image for a visa, master card, etc., if the credit card number is valid. If the user enters a wrong credit card number that doesn’t match the format of any credit card number, it shows a validation message.

Syntax

Users can follow the syntax below to use the react creditcard validator NPM package to validate the card number.

const {
   getCardNumberProps,
   getCardImageProps,
   meta: { erroredInputs },
} = useCreditCardValidator();
<input {...getCardNumberProps()} />
<small>{erroredInputs.cardNumber && erroredInputs.cardNumber}</small> 

In the above syntax, we have imported some methods from the useCreditCardValidator() class and passed them as input props.

Example

In the example below, we have imported the useCreditCardValidator from the NPM package. In the App component, we use the getCardNumberProps() method with the input which validates the credit card number.

Whenever a user enters the wrong credit card number, it shows that it is invalid.

import React from "react";
import { useCreditCardValidator, images } from "react-creditcardvalidator";
function App() {
   const {
      getCardNumberProps,
      getCardImageProps,
      meta: { erroredInputs },
   } = useCreditCardValidator();
   return (
      <div>
         <h3>
            {" "}
            Using the <i> React Creditcard Validator NPM package </i> to validate credit card number in ReactJS {" "}
         </h3>
         <div>
            <input {...getCardNumberProps()} /> {" "}
            <svg {...getCardImageProps({ images })} />
            <br />
            <small> {erroredInputs.cardNumber && erroredInputs.cardNumber} </small>
         </div>
      </div>
   );
}
export default App; 

Output

Use Validator NPM Package

Users can execute the command below to use the validator NPM package in the react project.

npm i validator 

Syntax

Users can follow the syntax below to use the isCreditCard() method to validate the credit card number.

let isValid = validator.isCreditCard(value); 

In the above syntax, we have passed the credit card number as a parameter of the isCreditCard() method to validate.

Example

In the example below, we have used the HTML input to take credit card number input. Whenever the user changes the value of the credit card input, it invokes the handleCreditCard() function, which uses the isCreditCard() method of the validator NPM package to validate the credit card number.

import React, { useState } from "react";
import validator from "validator";
function App() {
   let [cardNumber, setCardNumber] = useState("");
   let [message, setMessage] = useState("");
   function handleCreditCard(event) {
      let value = event.target.value;
      setCardNumber(value);
      if (validator.isCreditCard(value)) {
         setMessage("is a valid credit card number");
      } else {
         setMessage("is not a valid credit card number");
      }
   }
   return (
      <div>
         <h3>
            {" "}
            Using the <i> Validator NPM package </i> to validate the credit card number in ReactJS. {" "}
         </h3>
         <input type = "number" value = {cardNumber} onChange = {handleCreditCard} />
         <p>
            {" "}
            {cardNumber} {message}
         </p>
      </div>
   );
}
export default App;

Output

Creating the custom credit card validation algorithm using Luhn’s algorithm

This approach will use a custom algorithm to validate the credit card number from scratch. The valid credit card number should pass Luhn’s algorithm and follow the below rules.

  • Visa cards should start with the 4, and the length should be 13 or 16.

  • The master card should start with 51 through 55, and the length should be 16 digits.

  • American Express card should start with 34 or 37, and the length should be 15.

Syntax

Users can follow the algorithm below to use Luhn’s algorithm to validate the credit card number.

for (let i = cardNumber.length - 1; i >= 0; i--) {
   let digit = parseInt(cardNumber.charAt(i));
   if (shouldDouble)
   if ((digit *= 2) > 9) digit = digit - 9;
   sum += digit;
   shouldDouble = !shouldDouble;
}
let isValid = sum % 10 === 0; 

We have explained the above syntax via the example below.

Steps

Step 1 − Define the sum and shouldDouble variables, and initialize them with 0 and false, respectively.

Step 2 − Use the for loop to iterate through every digit of the card number from the end.

Step 3 − Get the digit value using its ASCII code and parseInt() method.

Step 4 − If the value of shouldDouble is true, Double the digits, and if the double value is greater than 9, subtract the 9 from the double value.

Step 5 − Add the final digit value to the sum variable.

Step 6 − Alter the value of shouldDouble as we need to double the digit alternatively.

Step 7 − Once the iteration of for loop is complete, check if the sum is divisible by 10 using the modulo operator, It means the credit card number passed Luhn’s test.

Example

In the example below, we have implemented the above algorithm in the validateByLuhn() function. In the validateCreditCard() function, we validate the number using Luhn’s algorithm. After that, we use the ternary operator to check if the number follows the rules of any credit card number.

For example, if the card length is 15, It should start with 34 or 37. If the card length is 16, it should start with 4 or 51 through 55.

import React, { useState } from "react";
function App() {
   let [cardNumber, setCardNumber] = useState("");
   let [message, setMessage] = useState("");
   
   // function to validate credit card numbers using the Luhn algorithm
   function validateByLuhn(cardNumber) {
      let sum = 0;
      let shouldDouble = false;
      for (let i = cardNumber.length - 1; i >= 0; i--) {
         let digit = parseInt(cardNumber.charAt(i));
         if (shouldDouble) { 
            if ((digit *= 2) > 9) digit = digit - 9;
         }
         sum = sum + digit;
         shouldDouble = !shouldDouble;
      }
      return sum % 10 === 0;
   }
   function validateCreditCard(event) {
      let cardNumber = event.target.value;
      setCardNumber(cardNumber);
      let isValid =
      (validateByLuhn(cardNumber) &&
      cardNumber.length == 15 &&
      (cardNumber.indexOf("34") == 0 || cardNumber.indexOf("37") == 0)) ||
      (cardNumber.length == 13 && cardNumber[0] == 4) ||
      (cardNumber.length == 16 &&
      (cardNumber[0] == 4 ||
      (cardNumber[0] == 5 && cardNumber[1] >= 1 && cardNumber[1] <= 5)));
      if (isValid) {
         setMessage("Valid Card Number");
      } else {
         setMessage("Invalid Card Number");
      }
   }
   return (
      <div>
         <h3>
            {" "}
            Using the <i> Luhn algorithm </i> to validate credit card number in ReactJS.{" "}
         </h3>
         <input type = "number" value = {cardNumber} onChange = {validateCreditCard} />
         <p> {message} </p>
      </div>
   );
}
export default App; 

Output

Updated on: 06-Mar-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements