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
SHA-2 vs. SHA-1: The Complete Rundown
Devoting 30% of Your Income to Rent Is Becoming the Norm in the U.S.
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Self-guided tour (for students) – Teaching & Learning Support
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
How To Cut Eelgrass Grounded
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Dmv In Anoka
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Umn Biology
Obituaries, 2001 | El Paso County, TXGenWeb
Cvs Sport Physicals
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Colin Donnell Lpsg
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Electric Toothbrush Feature Crossword
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Used Curio Cabinets For Sale Near Me
San Pedro Sula To Miami Google Flights
Selly Medaline
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.