Zend_Validate for the win
Join the DZone community and get the full member experience.
Join For FreeZend_Validate is a component of Zend Framework which provides validation classes which out-of-the-box enable you to check from string lengths to stranger properties like conformance to regular expressions or to a standard for barcodes.
Zend_Validate is quite peculiar with respect to other validation mechanisms, like Doctrine 1's native support for type validation of database column values. In fact, Zend_Validate contains many domain-specific validators, which have been contributed by the framework users in the last years. Since these kinds of validation are complex and error-prone to implement, it may be good to have them at your disposal in a framework you already have installed, for example to gain an MVC structure.
Some parts of Zend_Validate are quite complex, and tie-in with the other components: there are file-related validations on size, hash and more to attach to your forms; in the domain-specific category instead, we can find validator for credit card numbers consistency, or barcodes; isbn codes; and more..
These validators are usually implemented with a best-effort policy, since these values are built carrying a checksum (like the last cypher of an ISBN code), so that even if you do not connect to a database containing all the published books on Earth, if an user misses a cypher of the code the validator will catch it due to the inconsistency with the other segments of the string.
Composite pattern (aka validation chains)
Thus these validation types become commodities in Zend Framework. However, I think much of the power of Zend_Validate resides in the object-oriented interface it provides, and not in the domain-specific code which is quite strange to find in a framework, instead of a specialized library.
Zend_Validate_Interface, the only interface of the component, has many implementations. Some of them, like the Float or InArray validators, can be written in 5 minutes by wrapping PHP functions or with regular expressions (if you know the right regular expression to user, of course).
However, they are already present in the framework with a standard interface, that allows them to be easily chained. The various configuration parameters of the validators are passed to them in the constructor, or equivalently via setters, so that the isValid() method will always have the same interface no matter which validator you want to call or change in the chain.
The chain of validators is an instance of the class Zend_Validate, and it is an implementation of the Composite pattern: if you depend on a Zend_Validate_Interface in your client code, you'll never have to worry if you're passed a single validator (Zend_Validate_* instance) or a chain (Zend_Validate instance), or even a chain of chains.
Examples
The code sample will show you how to get started with Zend_Validate, along with the usage of validator chaining. The earlier examples are nothing to wonder about - but the chaining ones are an handy way to build endless different combinations of validators, or to reuse existing Composite validators and specify them even more.
<?php
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . '/home/giorgio/code/zftrunk/library');
require_once 'Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
class ZendValidateTest extends PHPUnit_Framework_TestCase
implements Zend_Validate_Interface
{
public function testAlphanumericValidation()
{
$validator = new Zend_Validate_Alnum();
$this->assertTrue($validator->isValid('giorgio88'));
$this->assertFalse($validator->isValid('giorgio 88'));
}
public function testAlphanumericValidationWithSpaces()
{
$validator = new Zend_Validate_Alnum();
$validator->setAllowWhiteSpace(true);
// or:
// new Zend_Validate_Alnum(array(
// 'allowWhiteSpace' => true
// ));
// setters and constructor options are equivalent
// and setters Api documentation describes which options
// are accepted (unified constructor)
$this->assertTrue($validator->isValid('giorgio 88'));
$this->assertFalse($validator->isValid('name@email.com'));
}
public function testBetweenValidation()
{
$validator = new Zend_Validate_Between(array(
'inclusive' => true,
'max' => 10,
'min' => 5
));
$this->assertTrue($validator->isValid(5));
$this->assertFalse($validator->isValid(4));
$this->assertTrue($validator->isValid(10));
$this->assertFalse($validator->isValid(11));
}
public function testEmailAddress()
{
$validator = new Zend_Validate_EmailAddress();
$this->assertTrue($validator->isValid('name@email.com'));
$this->assertFalse($validator->isValid('name.email.com'));
}
public function testIpValidation()
{
$validator = new Zend_Validate_Ip();
$this->assertTrue($validator->isValid('127.0.0.1'));
$this->assertFalse($validator->isValid('568.0.0.1'));
}
public function testInArray()
{
$validator = new Zend_Validate_InArray(array(
'haystack' => array('blue', 'red', 'green')
));
$this->assertTrue($validator->isValid('red'));
$this->assertFalse($validator->isValid('yellow'));
}
public function testRegex()
{
$validator = new Zend_Validate_Regex(array(
'pattern' => '/^[A-Z]*$/'
));
$this->assertTrue($validator->isValid('UPPER'));
$this->assertFalse($validator->isValid('lower'));
}
// an example from the manual, expanded a lot
public function testValidatorsChaining()
{
// let's say a nickname for our website should be like this:
$validatorChain = new Zend_Validate();
$validatorChain->addValidator(new Zend_Validate_NotEmpty(),
$breakChainOnFailure = true)
->addValidator(new Zend_Validate_StringLength(array(
'min' => 6
)))
->addValidator(new Zend_Validate_Alnum())
->addValidator($this);
// NotEmpty fails, and no one else is called:
$this->assertFalse($validatorChain->isValid(''));
// StringLength fails:
$this->assertFalse($validatorChain->isValid('nick'));
// Alnum fails:
$this->assertFalse($validatorChain->isValid('nickname%'));
// Passes all checks:
$this->assertTrue($validatorChain->isValid('giorgiosironi'));
return $validatorChain;
}
/**
* @depends testValidatorsChaining
*/
public function testChainsCanBeElementsOfOtherChains($originalValidatorChain)
{
$validatorChain = new Zend_Validate();
$validatorChain->addValidator($originalValidatorChain)
->addValidator($this);
// still not valid
$this->assertFalse($validatorChain->isValid(''));
$this->assertFalse($validatorChain->isValid('nick'));
$this->assertFalse($validatorChain->isValid('nickname%'));
// additional check from $this->isValid():
$this->assertFalse($validatorChain->isValid('theAdministrator'));
// still passes:
$this->assertTrue($validatorChain->isValid('giorgiosironi'));
}
/**
* Implementing Zend_Validate_Interface.
* Excludes reserved nicknames, like the ones containing 'admin'.
*/
public function isValid($value)
{
return !stristr($value, 'admin');
}
/**
* Required by the interface for displaying error messages,
* but not called nor explained here.
*/
public function getMessages()
{
return array('reserved');
}
}
Opinions expressed by DZone contributors are their own.
Comments