How to validate a credit card number in 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 entered credit card number and check whether it is valid or not using the npm module in the ReactJS application.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app creditcardvalidatedemo
Step 2: After creating your project folder i.e. creditcardvalidatedemo, move to it using the following command:
cd creditcardvalidatedemo
Step 3: After creating the ReactJS application, Install the validator module using the following command:
npm install validator
Project Structure: It will look like the following

Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code to validate credit card numbers with basic UI.
Javascript
import React, { useState } from "react" ; import validator from 'validator' const App = () => { const [errorMessage, setErrorMessage] = useState( '' ) const validateCreditCard = (value) => { if (validator.isCreditCard(value)) { setErrorMessage( 'Valid CreditCard Number' ) } else { setErrorMessage( 'Enter valid CreditCard Number!' ) } } return ( <div style={{ marginLeft: '200px' , }}> <pre> <h2>Validating CreditCard in ReactJS</h2> <span>Enter CreditCard: </span><input type= "text" onChange={(e) => validateCreditCard(e.target.value)}></input> <br /> <span style={{ fontWeight: 'bold' , color: 'red' , }}>{errorMessage}</span> </pre> </div> ); } export default App |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
- The following will be the output if the user enters an invalid credit card number as shown below:
- The following will be the output if the user enters a valid credit card number as shown below: