If you’re creating a payment form you may need to validate a credit card’s number, here comes the Luhn formula.
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:
- CakePHP
- marvinlabs/laravel-luhn
- luhn NPM package (NodeJS)
- Java Luhn package (Maven)
- theplant/luhn (Go)
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!
🥳