Skip to content

Luhn Validation

Shesh Ghimire edited this page Sep 13, 2024 · 1 revision

Preface

The abstract CardType::isNumberValid() method internally uses CardType::matchesLuhnAlgorithm($cardNumber, $shouldRun = true) method to validate Luhn Algorithm.

💡 Luhn validation only fails when $shouldRun is set to true and Luhn Algorithm package is installed and it's validation fails.

🎉 In every other scenario, the Luhn Validation always passes.

In order to override this behavior, you will need to extend the abstract class with your own implementation.

Validation always pass

In this case, you do not need to do anything, except NOT INSTALLING Luhn Algorithm package.

Validation based on custom logic

In this case, you also do not need to install the Luhn Algorithm package but you will need to create a new class to build your own custom logic.

namespace App\Validation;

use TheWebSolver\Codegarage\PaymentCard\CardType;

class CustomCard extends CardType {
    public static function matchesLuhnAlgorithm( string $value, bool $shouldRun = true ): bool {
        $isValidLuhn = self::someLogicToComputeLuhnAlgorithm();

        // If $shouldRun is explicitly set to "false", Luhn validation should always pass.
        // Otherwise, whatever custom logic you have implemented in above variable.
        return ! $shouldRun ? true : true === $isValidLuhn;
    }

    private static function someLogicToComputeLuhnAlgorithm(): bool {
        return false;
    }
}

In your application, use above CustomCard class to create a new Payment Card. Based on logic from above method CustomCard::someLogicToComputeLuhnAlgorithm() (which explicitly returns false), the Luhn validation should fail when the number is validated.

use App\Validation\CustomCard;

$americanExpressCard = (new CustomCard())
    // ...other setter methods.
    ->setLength([15])
    ->setIdRange([34, 37]);

$isValidCard = $americanExpressCard->isNumberValid(378282246310005); // false
Clone this wiki locally