Created
August 2, 2012 15:36
-
-
Save og-shawn-crigger/3238003 to your computer and use it in GitHub Desktop.
CI VIN Number Form Validation Callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //-------------------------------------------------------------------- | |
| /** | |
| * VIN Number Form Callback to verify that the VIN number is correct. | |
| * | |
| * Original VIN Check Code came from below link, no sense reinventing wheels | |
| * @link {http://stackoverflow.com/questions/3831764/php-vin-number-validation-code} | |
| * | |
| * @param string $vin VIN Number value sent from Form Validation Library. | |
| * | |
| * @return bool | |
| */ | |
| public function _vin_check($vin) | |
| { | |
| if ( ! preg_match('/^[^\Wioq]{17}$/', $vin)) | |
| { | |
| $this->form_validation->set_message('_vin_check', 'The %s is not the correct length.'); | |
| return FALSE; | |
| } | |
| $weights = array(8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2); | |
| $transliterations = array( | |
| "a" => 1, "b" => 2, "c" => 3, "d" => 4, | |
| "e" => 5, "f" => 6, "g" => 7, "h" => 8, | |
| "j" => 1, "k" => 2, "l" => 3, "m" => 4, | |
| "n" => 5, "p" => 7, "r" => 9, "s" => 2, | |
| "t" => 3, "u" => 4, "v" => 5, "w" => 6, | |
| "x" => 7, "y" => 8, "z" => 9 | |
| ); | |
| $sum = 0; | |
| for ($i = 0; $i < strlen($vin); $i++) | |
| { // loop through characters of VIN | |
| // add transliterations * weight of their positions to get the sum | |
| if ( ! is_numeric($vin{$i})) | |
| { | |
| $sum += $transliterations[$vin{$i}] * $weights[$i]; | |
| } | |
| else | |
| { | |
| $sum += $vin{$i} * $weights[$i]; | |
| } | |
| } | |
| // find checkdigit by taking the mod of the sum | |
| $checkdigit = $sum % 11; | |
| if ($checkdigit == 10) | |
| { // checkdigit of 10 is represented by "X" | |
| $checkdigit = "x"; | |
| } | |
| $valid = (bool) ($checkdigit == $vin{8}); | |
| // Need to Add Check for Correct VIN Number Here. | |
| if ($valid == FALSE) | |
| { | |
| $this->form_validation->set_message('_vin_check', 'The %s is not valid.'); | |
| return FALSE; | |
| } | |
| else | |
| { | |
| return TRUE; | |
| } | |
| }//end _vin_check() - Callback function | |
| //-------------------------------------------------------------------- | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There are problems with this code I believe 00000000000354888 would be considered valid . You should not use length of in the for loop as it could be changed while code is in motion .. always lowercase ?