PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Declaring Filter and Validator Rules

Before creating an instance of Zend_Filter_Input, declare an array of filter rules and an array of validator rules. This associative array maps a rule name to a filter or validator or a chain of filters or validators.

The following example filter rule set that declares the field 'month' is filtered by Zend_Filter_Digits, and the field 'account' is filtered by Zend_Filter_StringTrim. Then a validation rule set declares that the field 'account' is valid only if it contains only alphabetical characters.

<?php
$filters 
= array(
    
'month'   => 'Digits',
    
'account' => 'StringTrim'
);

$validators = array(
    
'account' => 'Alpha'
);

Each key in the $filters array above is the name of a rule for applying a filter to a specific data field. By default, the name of the rule is also the name of the input data field to which to apply the rule.

You can declare a rule in several formats:

  • A single string scalar, which is mapped to a class name.

    <?php
    $validators 
    = array(
        
    'month'   => 'Digits',
    );
  • An object instance of one of the classes that implement Zend_Filter_Interface or Zend_Validate_Interface.

    <?php
    $digits 
    = new Zend_Validate_Digits();

    $validators = array(
        
    'month'   => $digits
    );
  • An array, to declare a chain of filters or validators. The elements of this array can be strings mapping to class names or filter/validator objects, as in the cases described above. In addition, you can use a third choice: an array containing a string mapping to the class name followed by arguments to pass to its constructor.

    <?php
    $validators 
    = array(
        
    'month'   => array(
            
    'Digits',                // string
            
    new Zend_Validate_Int(), // object instance
            
    array('Between'112)  // string with constructor arguments
        
    )
    );

Note

If you declare a filter or validator with constructor arguments in an array, then you must make an array for the rule, even if the rule has only one filter or validator.

You can use a special "wildcard" rule key '*' in either the filters array or the validators array. This means that the filters or validators declared in this rule will be applied to all input data fields. Note that the order of entries in the filters array or validators array is significant; the rules are applied in the same order in which you declare them.

<?php
$filters 
= array(
    
'*'     => 'StringTrim',
    
'month' => 'Digits'
);

Zend Framework