Using Luhn’s algorithm to validate credit card numbers (and more) (2024)

Using Luhn’s algorithm to validate credit card numbers (and more) (2)

A bit of context

For context, the Luhn algorithm is a simple checksum formula that is used to validate a variety of identification numbers, such as credit card numbers, IBANs, IMEI numbers, and social security numbers.

The algorithm was invented by a computer scientist named Hans Peter Luhn in the 1950s.

Here is a link to Luhn’s algorithm Wikipedia page.

How does it work?

The Luhn algorithm works by summing up every other digit in the identification number, starting from the rightmost digit, and then doubling the value of every other digit and summing up the individual digits of the doubled values. Finally, the sum of both the previous steps is calculated, and the identification number is considered valid if the sum is a multiple of 10.

Here is a PHP implementation of this algorithm:

function luhn($number): bool
{
// Remove any spaces or non-digit characters
$number = preg_replace('/\D/', '', $number);
$sum = 0;
$alt = false;

for ($i = strlen($number) - 1; $i >= 0; $i--) {
$digit = intval($number[$i]);
if ($alt) {
$digit *= 2;
if ($digit > 9) {
$digit -= 9;
}
}
$sum += $digit;
$alt = !$alt;
}

return ($sum % 10 == 0);
}

Using Luhn in your projects

I’ll be showcasing the usage of the formula in Symfony, but it is of course possible to use it with other frameworks, and languages, there are a few links at the end of this paper.

If you’re working on a Symfony project, you can use the Luhn constraint to validate input with this formula, by either using it as an attribute on a class member or as a form validation constraint.

Here are two examples:

namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Transaction
{
#[Assert\Luhn(message: 'Please check your credit card number.')]
protected int $cardNumber;
}

class CreditCardType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('card_number', TextType::class, [
'constraints' => [
new Luhn([
'message' => 'Invalid credit card number',
]),
],
]);
}
}

Here are links to other implementations:

The Luhn formula is widely used in the verification of identification numbers, making it a very useful tool to master when writing code.

I hope this Story helped you understand the ins and outs of this algorithm.

If you liked this article, you may want to check my profile for more, I mostly write about programming and tech.

See you around, and have a good day!

🥳

Using Luhn’s algorithm to validate credit card numbers (and more) (2024)
Top Articles
Time for a Computer Reboot or Restart?
How to Gamify Debt Payoff to Make It Fun - Experian
Nullreferenceexception 7 Days To Die
Truist Bank Near Here
Uihc Family Medicine
12 Rue Gotlib 21St Arrondissem*nt
Kraziithegreat
Craigslist Pet Phoenix
What's Wrong with the Chevrolet Tahoe?
Joe Gorga Zodiac Sign
2021 Tesla Model 3 Standard Range Pl electric for sale - Portland, OR - craigslist
Sams Gas Price Fairview Heights Il
Caresha Please Discount Code
What to do if your rotary tiller won't start – Oleomac
Cooktopcove Com
Dumb Money
Kvta Ventura News
Nba Rotogrinders Starting Lineups
Michigan cannot fire coach Sherrone Moore for cause for known NCAA violations in sign-stealing case
Tnt Forum Activeboard
History of Osceola County
Q Management Inc
Craigslist Missoula Atv
Kayky Fifa 22 Potential
Ruse For Crashing Family Reunions Crossword
Gina Wilson All Things Algebra Unit 2 Homework 8
Masterkyngmash
Encore Atlanta Cheer Competition
Wemod Vampire Survivors
Intel K vs KF vs F CPUs: What's the Difference?
Craigslist Auburn Al
897 W Valley Blvd
Sinfuldeed Leaked
APUSH Unit 6 Practice DBQ Prompt Answers & Feedback | AP US History Class Notes | Fiveable
Red Sox Starting Pitcher Tonight
Cbs Trade Value Chart Week 10
Jay Gould co*ck
Aliciabibs
Mohave County Jobs Craigslist
Topos De Bolos Engraçados
Verizon Outage Cuyahoga Falls Ohio
Craigs List Hartford
Pulitzer And Tony Winning Play About A Mathematical Genius Crossword
Ihop Deliver
Barback Salary in 2024: Comprehensive Guide | OysterLink
Wrentham Outlets Hours Sunday
Craigslist Com Brooklyn
Powah: Automating the Energizing Orb - EnigmaticaModpacks/Enigmatica6 GitHub Wiki
How to Get a Check Stub From Money Network
Ret Paladin Phase 2 Bis Wotlk
Metra Union Pacific West Schedule
Southern Blotting: Principle, Steps, Applications | Microbe Online
Latest Posts
Article information

Author: Velia Krajcik

Last Updated:

Views: 5816

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Velia Krajcik

Birthday: 1996-07-27

Address: 520 Balistreri Mount, South Armand, OR 60528

Phone: +466880739437

Job: Future Retail Associate

Hobby: Polo, Scouting, Worldbuilding, Cosplaying, Photography, Rowing, Nordic skating

Introduction: My name is Velia Krajcik, I am a handsome, clean, lucky, gleaming, magnificent, proud, glorious person who loves writing and wants to share my knowledge and understanding with you.