DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Data
  4. Zend_Validate for the win

Zend_Validate for the win

Giorgio Sironi user avatar by
Giorgio Sironi
·
Dec. 02, 10 · Interview
Like (0)
Save
Tweet
Share
8.21K Views

Join the DZone community and get the full member experience.

Join For Free

Zend_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');
}
}
Framework Interface (computing) Database Composite pattern Data Types Strings Implementation Barcode Cards (iOS)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Browser Engines: The Crux of Cross-Browser Compatibility
  • Important Takeaways for PostgreSQL Indexes
  • Use AWS Controllers for Kubernetes To Deploy a Serverless Data Processing Solution With SQS, Lambda, and DynamoDB
  • ClickHouse: A Blazingly Fast DBMS With Full SQL Join Support

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: