initial commit
This commit is contained in:
50
app/Rules/LuhnValid.php
Normal file
50
app/Rules/LuhnValid.php
Normal file
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Rules;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Contracts\Validation\ValidationRule;
|
||||
|
||||
class LuhnValid implements ValidationRule
|
||||
{
|
||||
/**
|
||||
* Run the validation rule.
|
||||
*
|
||||
* @param string $attribute
|
||||
* @param mixed $value
|
||||
* @param \Closure(string): \Illuminate\Translation\PotentiallyTranslatedString $fail
|
||||
*/
|
||||
public function validate(string $attribute, mixed $value, Closure $fail): void
|
||||
{
|
||||
if (!$this->passes($attribute, $value)) {
|
||||
$fail('The :attribute is not a valid credit card number.');
|
||||
}
|
||||
}
|
||||
|
||||
public function passes($attribute, $value)
|
||||
{
|
||||
// Remove non-numeric characters
|
||||
$cardNumber = preg_replace('/\D/', '', $value);
|
||||
|
||||
$sum = 0;
|
||||
$shouldDouble = false;
|
||||
|
||||
// Process the digits from right to left
|
||||
for ($i = strlen($cardNumber) - 1; $i >= 0; $i--) {
|
||||
$digit = (int)$cardNumber[$i];
|
||||
|
||||
if ($shouldDouble) {
|
||||
$digit *= 2;
|
||||
if ($digit > 9) {
|
||||
$digit -= 9;
|
||||
}
|
||||
}
|
||||
|
||||
$sum += $digit;
|
||||
$shouldDouble = !$shouldDouble;
|
||||
}
|
||||
|
||||
// Return true if the total modulo 10 is 0
|
||||
return ($sum % 10 === 0);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user