A PHP VAT validation module for Zend_Validate
Filed under Zend Framework
Here is a simple way to validate VAT / TVA numbers from Europe Union (EU) countries using Zend_Validate.
Please feel free to comment!
<?php
class My_Validate_VAT extends Zend_Validate_Abstract
{
const VAT_LENGTH = 'VATLength';
private $locale = null;
private $VAT_min = null;
private $VAT_max = null;
public function __construct(){
$this->locale = Zend_Registry::get('Zend_Locale');
}
protected $_messageTemplates = array(
self::VAT_LENGTH => "The VAT code length is incorrect",
);
private function setLength(){
switch($this->locale->getRegion()){
case 'FR': $this->VAT_min = 13; $this->VAT_max = 13; break;
case 'BE': $this->VAT_min = 11; $this->VAT_max = 12; break;
case 'CH': $this->VAT_min = 0; $this->VAT_max = 12; break;
case 'DE': $this->VAT_min = 11; $this->VAT_max = 11; break;
case 'UK': $this->VAT_min = 5; $this->VAT_max = 14; break;
case 'NL': $this->VAT_min = 14; $this->VAT_max = 14; break;
default: $this->VAT_min = 10; $this->VAT_max = 15; break;
}
}
/**
* Defined by Zend_Validate_Interface
*
* Returns true if and only if $value is a valid IP address
*
* @param mixed $value
* @return boolean
*/
public function isValid($value)
{
$this->setLength();
$length = new Zend_Validate_StringLength($this->VAT_min, $this->VAT_max);
$filter = new Zend_Filter_Alnum();
$VAT = $filter->filter($value);
if($length->isValid($VAT) and substr($VAT,0,2) == $this->locale->getRegion()){
return true;
} else{
$this->_error(self::VAT_LENGTH);
return false;
}
return true;
}
}
Sep24