Skip to end of metadata
Go to start of metadata
You are viewing an old version of this page. View the current version. Compare with Current  |   View Page History

<ac:macro ac:name="unmigrated-inline-wiki-markup"><ac:plain-text-body><![CDATA[

Zend Framework: Zend_Validate_Builder, Zend_Filter_Builder Component Proposal

Proposed Component Name Zend_Validate_Builder, Zend_Filter_Builder
Developer Notes, Zend_Filter_Builder
Proposers Bryce Lohr
Revision 0.3 (wiki revision: 47)

Table of Contents

1. Overview

This proposal is simply an alternative to the Zend_Filter_Input proposal. Bill Karwin and others have put a lot of time and energy into that work, and I'd like to take this opportunity to thank them. This work is built upon those, and I'd like to acknowledge that up front.

This was originally inspired by Christopher Thompson's Zend_FilterChain proposal, and provides a vaguely similar interface. This takes quite a different tact than the array-driven structure used by Zend_Filter_Input; some people may find the code-driven interface preferable.

Here's a quick rundown of the major parts:

  • Zend_Filter_Builder and Zend_Validate_Builder classes
  • Facades providing a fluent interface for both Builder classes
  • An Error Manager class to facilitate configuring error messages for many validators at once, as well as retrieving raised errors

2. References

3. Component Requirements, Constraints, and Acceptance Criteria

  • Zend_Validate_Builder manages exactly one responsibility: validating sets of data in arrays
  • Zend_Filter_Builder manages exactly one responsibility: filtering sets of data in arrays
  • Zend_Validate_Builder_ErrorManager is responsible for defining and reporting error messages for validators
  • Neither component handles any other aspect of form processing
  • No mechanism for statically calling filters or validators is provided (out of scope)
  • This solution is not designed to make it easier to use single filters or validators; rather, it automates using many filters/validators together on whole sets of data
  • This is compatible with the existing Zend_(Validate|Filter)_Interface API; i.e., existing Framework filters and validators will work without being modified

4. Dependencies on Other Framework Components

  • Zend_Validate_Interface
  • Zend_Filter_Interface
  • Zend_Validate_*
  • Zend_Filter_*
  • Zend_Validate_Exception

5. Theory of Operation

Essentially, Zend_Validate_Builder and Zend_Filter_Builder use the Builder and Composite patterns to construct a recursive tree structure of Zend_Validate_* or Zend_Filter_* instances, which is then applied wholesale to an array of input data. In the case of Zend_Filter_Builder, the result is the original input array after having each of the constituent filters applied to each input array element. In the case of Zend_Validate_Builder, the result is a boolean value indicating whether any single element in the input data was deemed invalid by any of the constituent Zend_Validate_* instances.

In addition to the Builder classes, there are also Zend_Validate_Builder_FluentFacade and Zend_Filter_Builder_FluentFacade. These classes provide a very elegant and easy to use fluent interface to the Builder classes, and their use is totally optional. The Builder classes in no way depend on these.

Error messages are a vital part of data validation. If your code decides that something the user entered is not acceptable, you must be able to tell the user why. The Zend_Validate_Builder_ErrorManager class addresses this concern. It provides a way for the Zend_Validate_* classes, Zend_Validate_Builder, and your application code to define and communicate error messages. The Zend_Validate_* classes all have built-in error messages which, for a variety of reasons, are often not suitable to display directly to users. Therefore, the error messages for validators can be overridden. However, this must be done manually, on each individual instance with the built-in validators. Zend_Validate_Builder_ErrorManager allows you to define all the error messages for any arbitrary set of validators, by data field. This way, you can easily set up each error message for a field, and also easily retrieve any error messages by field for display.

6. Milestones / Tasks

  • Milestone 1: [DONE] Design interface and test feasibility
  • Milestone 2: [DONE] Write proposal
  • Milestone 3: [DONE] Gather feedback and revise design as necessary (done, but
    more feedback is always welcomed)
  • Milestone 4: [DONE] Develop full implementation and unit tests
  • Milestone 5: Write documentation (this proposal actually is the current documentation)

7. Class Index

  • Zend_Validate_Builder
  • Zend_Validate_Builder_FluentFacade
  • Zend_Validate_Builder_FluentAdder
  • Zend_Validate_Builder_ValidatorFactory
  • Zend_Validate_Builder_ValidatorFactory_Interface
  • Zend_Validate_Builder_ErrorManager
  • Zend_Validate_Builder_ErrorManager_Interface
  • Zend_Filter_Builder
  • Zend_Filter_Builder_FluentFacade
  • Zend_Filter_Builder_FluentAdder
  • Zend_Filter_Builder_FilterFactory
  • Zend_Filter_Builder_FilterFactory_Interface

8. Use Cases

For all of these use cases, assume that the code shown is extracted from a class that is processing a form, with the intention of saving the data to the database. Assume that methods referenced after $this-> exist and are valid; variables such as $post pretty obviously refer to the user-submitted data. In most of these examples, I refer to Zend_Validate_* classes that don't exist in the Framework. Many of them are available in the Laboratory, along side ZVB and ZFB; as for the others--just assume they exist for now.


Some very basic examples. First, Zend_Filter_Builder:

This filters out all non-digit characters from the phone_no field, and strips HTML tags from the description field. The filter() method takes an array of data, and runs the specified filters on the matching keys.

Next, Zend_Validate_Builder:

Here, the phone_no field is checked to make sure it's numeric, and description field is checked to make sure it's less than 255 characters long. Since the Zend_Validate_* classes will usually fail an empty value, all fields are required by default. The add method takes an optional third argument, which are flags for that specific combination of field and validator. We're passing the OPTIONAL flag for the description field, so Zend_Validate_Builder will skip over it when it's empty, and the StringLength validator will never see it unless it has a value.

Note the phone_no example: the order the validators are added to the field is preserved; that is, the IsNumeric validator will be run before the Between validator. All the validators assigned to a field will always be executed. Therefore, a single field might generate several error messages, depending on how many validators it fails. Since these error messages are built up in the Error Manager object, your application code can decide which errors to display to the user; you need not display all of them.


This demonstrates a little more advanced usage.

Pattern matching:

Specifying the PATTERN flag causes the Builder classes to interpret the field name argument as a PCRE regex to be matched against input field names. The given validator or filter is applied to each matching field.

Validating each field in a list:

Processing arrays of patterns (i.e., array in 2nd parm, with PATTERN flag in 3rd) is currently not supported. However, it is possible (and likely) to be added in the future.

Since this follows the Composite pattern, you can nest validators to do some neat things. In this example, assume we're trying to validate a mailing address. Suppose, for organizational purposes, you structured the form so the mailing address was in a sub-array, something like this:

You could validate this nested structure like so:

If you have a situation where the entire address is optional, you might be temped to pass the OPTIONAL flag to the address field. However, that won't work: when the OPTIONAL flag is set, the Builder checks the value of the current field, and if it's blank, the Builder never calls the validator. Here, the current field would be a six-element array, which will never be considered empty. The elements might be empty, but the array itself won't be. Therefore, the entire address field will always be validated against the sub-validator. In this situation, what you actually need is conditionally optional fields, which requires completely different logic.


Password confirmation, catpcha validation, etc. This uses the PASS_GROUP flag, and a pair of similar validators called Zend_Validate_Equals and Zend_Validate_AllEqual. Zend_Validate_Equals takes a scalar value and compares it to a standard value passed to the constructor. Zend_Validate_AllEqual takes an array, and returns true if all of its elements equal each other. Both of these can be found in the Laboratory, and both optionally support strict type checking, which is false by default. The PASS_GROUP flag allows you to tell the Builder to pass all the fields named in the second parameter as a single array to the validator. This is handy for validators like Zend_Validate_AllEqual, which examine the contents of several fields in the input to decide if they are valid.

Password Confirmation:

Catpcha validation:


In order to handle a situation like the optional address mentioned above, you'd need something like this. This uses another new validator called Zend_Validate_AllOrNone. It allows you to make some fields conditionally required. You pass it a set of fields, and will consider them valid under two distinct cases: if either all of them are empty, or if all of them are filled. If only some are filled, then it considers the set invalid. To get the most benefit from this, combine it with other validators. The example may clarify things a bit. This validator can be found in the Laboratory, with the Builder classes.

Here, the OPTIONAL flag is passed to all the validators after the AllOrNone validator. This is so those validators don't fail the field in the case when the field is omitted (the fields are still opitonal; albeit conditionally optional).


Zend_Validate_Builder and Zend_Filter_Builder really promote composing together validators to do interesting things. Here are some examples that show some of neat things that can be done with custom "Decorator" validators. Keep in mind that a Zend_Validate_Builder instance counts as a validator that can be decorated; if you're creative, you can probably come up with some really cool things to do with this.

Most validators only take a scalar value to isValid. Zend_Validate_Array turns an exisiting scalar validator into an array validator. You pass a validator to the constructor, and an array value to isValid. It will then iterate over all the elements of the array, performing the given validator on each one. Obviously, you could nest these as much as you needed to, provided that you know the structure of the input array ahead of time.

Zend_Validate_AtLeastN and Zend_Validate_AtMostN
These two are decorating array validators. They expect an array passed to isValid, a validator instance passed to the constructor, and check that at least (or at most) n elements in the array pass the validator. This works great with the PASS_GROUP flag when your input data doesn't already have an array in it.

I haven't come up with a good, realistic example for this, but there's a lot of creative potential here. Also remember that you don't have to always use these two together as I have here. All three of these validators are in the Laboratory.


I used to build forms that mimiced my table structure, with the ability to edit multiple records for multiple tables in one form. In this example, assume we want to validate a CRUD form for a simple contact table, but the user can add multiple contacts on the form (with the help of some Javascript in UI). The form fields are laid out in a three-dimensional array, where the first key is the table name, the second key is the row number, and the third key is the field name. It would result in post data that looks something like this:

Assume that the user actually entered several contacts, so the 'contacts' array would have several sub-arrays, one for each record, just like a DB query result set.

Here's how to set up a filter/validator that would process all of the records:


So where have the error messages from all these validators been going all this time? To the Error Manager! This shows how to use the Error Manager both to retrieve raised errors, and define custom error messages.

The Zend_Validate_Interface interface defines the method getMessages, which returns an array of all the error messages raised by the validator, indexed by error code. Zend_Validate_Builder implements this method (albeit, with an incompatible return value), which you can use to retrieve all the error messages that have been raised during the entire validation run. Internally, it delegates this work to the Error Manager; so for retrieving messages, you don't need to touch it directly. You only need to access the Error Manager directly when you want to use it set up custom error messages, or want more control over which errors are returned.

Retreiving errors
Normally, calling getMessages on a validator returns a flat array of error messages. But because the Builder manages a whole collection of fields and validators, it's return value is slightly different. It returns a three-dimensional array, indexed by field name, validator class name, and failure reason code. Say the user entered a value in the name field that was too short:

Of course, if there were other fields and validators that failed, their messages would all be in the returned array, under the appropriate index.

Custom error messages
You can grab an instance of the Error Manager object to set any number of custom error messages for any combination of field, validator, and failure reason code.

The Error Manager provides a hasMessages method, in addition to getMessages. Both of these methods take optional arguments that allow you to filter down to a particular subset of the error messages you might be interested in.

One key benefit of all this is that it allows you to completely separate your error messages from the code that does validation. You could put all your messages in a separate file, or use a Zend_Config object to load all the error messages for a form at once. Among other things, this should make I18N much easier.

Here's one possible way to store errors in an INI file, and set them via Zend_Config. The setTemplates method makes this possible, since it accepts an entire array structure of error messages.




This use case is more real-world. I'm writing a financial system which consists of individual applications for General Ledger, Accounts Payable, Accounts Receiveable, etc., along with some applications, such as Privilege Licenses, which are designed for local governments. These examples are adapted from some of the Privilege Licenses code (obviously, it's not the actual application code).

This is from a form that allows entry of new License Codes. There are quite a few complex validation requirements on this form. The amount and rate_schedule fields are mutually exclusive. There are seven account number fields, where each account number field actually consists of two fields: one for the Entity (Company) and one for the Account Number. Account numbers are only valid by Entity.

The seven account fields have several complex requirements. The Cash and Revenue accounts are always required. The Due To and Due From accounts are required only if the Cash Ent and Revenue Ent are different, or (if given) the Cash Ent and AR Ent are different. If present, the Cash Ent and Due To Ent must match each other, and the AR Ent, Reserve AR Ent, Due From Ent, and Prepaid Ent must all match.

I've omitted all but the validate() method for the sake of clarity.


The fluent interface. This demonstrates the fluent Facade by re-writing UC-07. A lot of the "fluency" of the interface depends quite a bit on the naming of the filter and validator classes.


And finally, the big one, re-written with the fluent Facade. A bit less big now.

Namespaces and Class names
The factories used by the fluent Facades attempt to find classes by searching through an array of namespace prefixes. If you have filter or validator classes with the same "base name" in two different namespaces, only the first one found will be returned. There's no way to pick which namespace to use on a call-by-call basis. You can easily replace the factories with your own in order to implement different instantiation rules. The standard Builder classes are not affected by this problem.

9. Class Skeletons













Get the Code!
The full implementation of these classes can be checked out from the Zend Laboratory SVN repository: The source code is in the library/Zend/Filter and library/Zend/Validate directories. The unit tests are in tests/Zend/Filter and tests/Zend/Validate.


Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.