00001 <?php 00002 00027 require_once 'Zend/Validate/Abstract.php'; 00028 00029 00036 class Zend_Validate_Ccnum extends Zend_Validate_Abstract 00037 { 00041 const LENGTH = 'ccnumLength'; 00042 00046 const CHECKSUM = 'ccnumChecksum'; 00047 00053 protected static $_filter = null; 00054 00060 protected $_messageTemplates = array( 00061 self::LENGTH => "'%value%' must contain between 13 and 19 digits", 00062 self::CHECKSUM => "Luhn algorithm (mod-10 checksum) failed on '%value%'" 00063 ); 00064 00073 public function isValid($value) 00074 { 00075 $this->_setValue($value); 00076 00077 if (null === self::$_filter) { 00081 require_once 'Zend/Filter/Digits.php'; 00082 self::$_filter = new Zend_Filter_Digits(); 00083 } 00084 00085 $valueFiltered = self::$_filter->filter($value); 00086 00087 $length = strlen($valueFiltered); 00088 00089 if ($length < 13 || $length > 19) { 00090 $this->_error(self::LENGTH); 00091 return false; 00092 } 00093 00094 $sum = 0; 00095 $weight = 2; 00096 00097 for ($i = $length - 2; $i >= 0; $i--) { 00098 $digit = $weight * $valueFiltered[$i]; 00099 $sum += floor($digit / 10) + $digit % 10; 00100 $weight = $weight % 2 + 1; 00101 } 00102 00103 if ((10 - $sum % 10) % 10 != $valueFiltered[$length - 1]) { 00104 $this->_error(self::CHECKSUM, $valueFiltered); 00105 return false; 00106 } 00107 00108 return true; 00109 } 00110 00111 }