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
Validate GB VAT numbers
Moderator: General Moderators
- Maugrim_The_Reaper
- DevNet Master
- Posts: 2704
- Joined: Tue Nov 02, 2004 5:43 am
- Location: Ireland
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:
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
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;
}Enjoy
- Maugrim_The_Reaper
- DevNet Master
- Posts: 2704
- Joined: Tue Nov 02, 2004 5:43 am
- Location: Ireland
- Maugrim_The_Reaper
- DevNet Master
- Posts: 2704
- Joined: Tue Nov 02, 2004 5:43 am
- Location: Ireland