Overview
In this exercise, you will build a React Credit Card Validator 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
A simple checksum formula, Luhn’s algorithm validates credit card numbers and other types of identification numbers. They named the algorithm 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. Multiply each digit by 2 if its position is even (counting from the rightmost digit as position 1) and by 1 if its position is odd. If the multiplication product exceeds 9, add the two digits of the product together to produce a single digit.
Once you have multiplied and added together all of the digits, divide the sum by 10. If the division leaves a remainder of 0, then Luhn’s algorithm considers the credit card number valid.
Here’s an example of how Luhn’s algorithm works with a sample credit card number, 1234567890123456:
- 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.
- The next digit to the left is 5. This digit is multiplied by 1, because its position is odd. The result is 5.
- The next digit to the left is 4. This digit is multiplied by 2, because its position is even. The result is 8.
- Continuing in this way, we get: 1+6+5+1+8+7+3+4+1+6+5+0+3+4+2+5 = 66
- 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.
Instructions for React Credit Card Validator
- Create a new React component called
CreditCardValidator
. - Add an input field where users can enter their credit card number.
- Add a button that will trigger the validation process when clicked.
- Implement Luhn’s algorithm to validate the credit card number.
- Display a message indicating whether the credit card number is valid or not.
- Style the component to make it look like a credit card.
Bonus Requirements
- Add support for multiple credit card types (Visa, Mastercard, etc.).
- 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 = event.target.value.replace(/\D/g, ''); // replace any non-numeric characters
setCreditCardNumber(input);
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) {
setIsValid(false);
return;
}
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';
default:
return 'Unknown';
}
}
return (
<div className="credit-card-container">
<div className="credit-card-input-container">
<input
type="text"
pattern="[0-9]*"
className="credit-card-input"
placeholder="Enter your credit card number"
value={creditCardNumber}
onChange={handleInputChange}
/>
<button className="credit-card-button" onClick={handleValidation}>Validate</button>
</div>
{isValid === false && <div className="credit-card-error">Invalid Credit Card</div>}
{isValid === true && <div className="credit-card-success">Valid {cardType} Credit Card</div>}
</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 />
</div>
);
}
export default App;
Applications where the Credit Card Validator can be used
- 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. - 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. - 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. - 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 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. Do not use this component 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.
Conclusion
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!
Boost your React skills with 25 React JavaScript Practice Exercises with Solutions hands-on challenges to master components, hooks, and more!