Page 1 of 1
Validate GB VAT numbers
Posted: Thu Apr 06, 2006 4:06 am
by phpScott
All right you brainy British programmers.
Do any of you know of any simple validation routines to validate a UK VAT number.
I've seen the one on phpclasses and it is complete overkill for what I need, this is for a British site that will only be accepting British customers so EU wide validation isn't necessary.
Any suggestions
Posted: Thu Apr 06, 2006 4:56 am
by timvw
If i'm not mistaken in pear there is a validation package too... With all the validation rules separated per country... So i guess it would be easier to borrow it from there... (If your licensing allows it)
Posted: Thu Apr 06, 2006 5:19 am
by phpScott
Just checked Validation for some but not for GB.
Thanks though.
Posted: Thu Apr 06, 2006 5:20 am
by Maugrim_The_Reaper
UK VAT numbers usually (or did last I checked) include a self validating calculation - the last two digits represent a fixed equation result based on the first 7 digits. Using this should in theory validate they are at least validly constructed - thereby meeting your filtering requirements.
There is one special case - child companies (subsidiaries usually) append an extra 3 digits (might want to drop these before the validation routine if included). It's also possible the number will be prefixed with "GB" which should also be excluded.
Now the formula...
The first 7 digits are multiplied in sequence by an inverse sequence 8-2. You substract 97 from the total of all such values until you reach a negative result. The inverse of the negative value must equal the final 2 digits of the VAT number. In PHP:
Code: Select all
function isValidUKVatFormat($vat) {
// strip GB prefix and any spaces first
$vat_fixed = str_replace(array('g','b','G','B'), '', preg_replace('/\s+/s', '', $vat));
$vat_validresult = substr($vat_fixed, 7, 2);
$vat_sequence = substr($vat_fixed, 0, 7);
$results = array();
for($i=8; $i>=2; $i--)
{
$pos = 8 - $i;
$results[] = $vat_sequence[$pos] * $i;
}
$result_total = array_sum($results);
while($result_total > 0)
{
$result_total -= 97;
}
$positivevalue = -1 * $result_total;
if($positivevalue == $vat_validresult)
{
return true;
}
return false;
}
This is what I've used for a while now, and until they start issuing new VAT sequences I think it's still valid for VAT numbers in the UK. The EU VAT number for UK companies (little bonus) is identical except it includes EU as a prefix. So the above works on those also. The regular EU vat numbers are not used in the UK.
Enjoy

Posted: Thu Apr 06, 2006 5:24 am
by Maugrim_The_Reaper
/me notes the above is free to use. Wrote it myself so have at it if you want it.
Posted: Thu Apr 06, 2006 7:49 am
by phpScott
thanks Maugrim that did the trick nicely. Thanks for the use I put your name in comments next to the function, Cheers.
Posted: Thu Apr 06, 2006 9:13 am
by Maugrim_The_Reaper
I finally get my genius recognised...

. Thanks.