I recently had to write some code to validate UK VAT number for a client – so I thought I’d share it to save a bit of time for anyone else who needed to do the same thing.
<?php
/*
* Class: vatnumbervalidator
* Author: Chris Wheeler
* Version: 1.0
* Date: 2009-10-15
*
* Validates VAT numbers, returns 1 if valid or 0 if invalid
*
* Usage Examples:
*
* vatnumbervalidator::check(922577120);
* vatnumbervalidator::check('922 5771 20');
* vatnumbervalidator::check('VAT Number #922 5771 20 ');
*
*/
class vatnumbervalidator {
public static function check($vatnumber) {
// cleanup the vat number to remove spaces or non-numeric characters
$v = vatnumbervalidator::clean($vatnumber);
// check length
if (strlen($v) < 9) {
return 0;
}
// calculate the total of each of the first 7 digits, multiplied by 8 descending to 2
$c = 0;
$i = 0;
for ($m=8; $m>=2; $m--) {
$c += ($v[$i] * $m);
$i++;
}
// subtrack 97 until the checksum is negative
while ($c >= 0) {
$c -= 97;
}
// inverse the checksum so it becomes positive
$c = $c / -1;
// if the checksum is equal to the last two digits of the number, return true
return ($c == $v[7] . $v[8]);
}
public static function clean($vatnumber) {
// remove all non numeric values
$v = preg_replace('/[^0-9]/', '', $vatnumber);
return $v;
}
}
?>
All feedback and comments appreciated!
