PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php use Illuminate\Contracts\Validation\Rule; class CreditCardNumber implements Rule { /** * Luhn algorithm * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { $length = strlen($value); $parity = $length % 2; $value = substr($value, 0, -1); $value = strrev($value); echo $value; $digits = collect(str_split($value))->reverse(); //$digits->pop(); //$digits = $digits->reverse(); echo $digits; $sum = $digits ->map(function ($value) { //echo (int)$value; return (int)$value; }) ->map(function ($value, $index) { return $value * (($index % 2 == 1) ? 2 : 1); //return ($index % 2 == $parity) ? $value * 2 : $value; }) ->map(function ($value) { //echo ($value > 9) ? $value - 9 : $value; return ($value > 9) ? $value - 9 : $value; }) ->sum(); //echo $sum % 10 == $digits->last(); return $sum % 10 == $digits->last(); //return ($sum % 10 == 0); } function is_valid_card($number) { // Strip any non-digits (useful for credit card numbers with spaces and hyphens) $number = preg_replace('/\D/', '', $number); // Set the string length and parity $number_length = strlen($number); $parity = $number_length % 2; // Loop through each digit and do the maths $total = 0; for ($i = 0; $i < $number_length; $i++) { $digit = $number[$i]; // Multiply alternate digits by two if ($i % 2 == $parity) { $digit *= 2; // If the sum is two digits, add them together (in effect) if ($digit > 9) { $digit -= 9; } } // Total up the digits $total += $digit; } // If the total mod 10 equals 0, the number is valid return ($total % 10 == 0) ? TRUE : FALSE; } /** * Get the validation error message. * * @return string */ public function message() { return 'The :attribute must be a valid creditcard number.'; } public function test() { $creditCardValidator = new CreditCardNumber(); //$creditCardNumber = '4065875212168008'; //$creditCardNumber = '4601841501612776'; $creditCardNumber = '4601841501612776'; // Validate the credit card number using the passes method if ($creditCardValidator->passes('credit_card_number', $creditCardNumber)) { echo "Validation passed: The credit card number is valid."; } else { echo "Validation failed: The credit card number is not valid."; } } public function test2() { $creditCardValidator = new CreditCardNumber(); //$creditCardNumber = '4065875212168008'; //$creditCardNumber = '4601841501612776'; $creditCardNumber = '4601841501612776'; // Validate the credit card if ($creditCardValidator->is_valid_card('credit_card_number', $creditCardNumber)) { echo "Validation passed: The credit card number is valid."; } else { echo "Validation failed: The credit card number is not valid."; } } } $validator = new CreditCardNumber(); $validator->test();
Show:  
Copy Clear