Friday, September 13, 2013

VIN Validation with PHP

Vehicle Identification Number Validation


$vin = '1G1YW2DW0A5108451';


function vinValidate($vin){
 
    $transliteration = 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,
    );

    $weights = array(8,7,6,5,4,3,2,10,0,9,8,7,6,5,4,3,2);
       
        $vin = strtoupper($vin);
        $length = strlen($vin);
        $sum = 0;

        if($length != 17)
        {
            return array('status'=>false, 'message'=>'VIN is not the right length');
        }

        for($x=0; $x<$length; $x++)
        {
            $char = substr($vin, $x, 1);

            if(is_numeric($char))
            {
                $sum += $char * $weights[$x];
            }
            else
            {
                if(!isset($transliteration[$char]))
                {
                    return array('status'=>false, 'message'=>'VIN contains an invalid character.');
                }

                $sum += $transliteration[$char] * $weights[$x];
            }
        }

        $remainder = $sum % 11;
        $checkdigit = $remainder == 10 ? 'X' : $remainder;

        if(substr($vin, 8, 1) != $checkdigit)
        {
            return array('status'=>false, 'message'=>'The VIN is not valid.');
        }

        return array('status'=>true, 'message'=>'The VIN is valid.');
    }
   



Thanks coderelic

No comments:

Post a Comment