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

Using Metacommands to Control Filter or Validator Rules

In addition to declaring the mapping from fields to filters or validators, you can specify some "metacommands" in the array declarations, to control some optional behavior of Zend_Filter_Input. Metacommands appear as string-indexed entries in a given filter or validator array value.

The FIELDS metacommand

If the rule name for a filter or validator is different than the field to which it should apply, you can specify the field name with the 'fields' metacommand.

You can specify this metacommand using the class constant Zend_Filter_Input::FIELDS instead of the string.

<?php
$filters 
= array(
    
'month' => array(
        
'Digits',        // filter name at integer index [0]
        
'fields' => 'mo' // field name at string index ['fields']
    
)
);

In the example above, the filter rule applies the 'digits' filter to the input field named 'mo'. The string 'month' simply becomes a mnemonic key for this filtering rule; it is not used as the field name if the field is specified with the 'fields' metacommand, but it is used as the rule name.

The default value of the 'fields' metacommand is the index of the current rule. In the example above, if the 'fields' metacommand is not specified, the rule would apply to the input field named 'month'.

Another use of the 'fields' metacommand is to specify fields for filters or validators that require multiple fields as input. If the 'fields' metacommand is an array, the argument to the corresponding filter or validator is an array of the values of those fields. For example, it is common for users to specify a password string in two fields, and they must type the same string in both fields. Suppose you implement a validator class that takes an array argument, and returns TRUE if all the values in the array are equal to each other.

<?php
$validators 
= array(
    
'password' => array(
        
'StringEquals',
        
'fields' => array('password1''password2')
    )
);
// Invokes hypothetical class Zend_Validate_StringEquals,
// passing an array argument containing the values of the two input
// data fields named 'password1' and 'password2'.

If the validation of this rule fails, the rule key ('password') is used in the return value of getInvalid(), not any of the fields named in the 'fields' metacommand.

The PRESENCE metacommand

Each entry in the validator array may have a metacommand called 'presence'. If the value of this metacommand is 'required' then the field must exist in the input data, or else it is reported as a missing field.

You can specify this metacommand using the class constant Zend_Filter_Input::PRESENCE instead of the string.

<?php
$validators 
= array(
    
'month' => array(
        
'digits',
        
'presence' => 'required'
    
)
);

The default value of this metacommand is 'optional'.

The DEFAULT_VALUE metacommand

If a field is not present in the input data, and you specify a value for the 'default' metacommand for that rule, the field takes the value of the metacommand.

You can specify this metacommand using the class constant Zend_Filter_Input::DEFAULT_VALUE instead of the string.

This default value is assigned to the field before any of the validators are invoked. The default value is applied to the field only for the current rule; if the same field is referenced in a subsequent rule, the field has no value when evaluating that rule. Thus different rules can declare different default values for a given field.

<?php
$validators 
= array(
    
'month' => array(
        
'digits',
        
'default' => '1'
    
)
);

// no value for 'month' field
$data = array();

$input = new Zend_Filter_Input(null$validators$data);
echo 
$input->month// echoes 1

If your rule uses the FIELDS metacommand to define an array of multiple fields, you can define an array for the DEFAULT_VALUE metacommand and the defaults of corresponding keys are used for any missing fields. If FIELDS defines multiple fields but DEFAULT_VALUE is a scalar, then that default value is used as the value for any missing fields in the array.

There is no default value for this metacommand.

The ALLOW_EMPTY metacommand

By default, if a field exists in the input data, then validators are applied to it, even if the value of the field is an empty string (''). This is likely to result in a failure to validate. For example, if the validator checks for digit characters, and there are none because a zero-length string has no characters, then the validator reports the data as invalid.

If in your case an empty string should be considered valid, you can set the metacommand 'allowEmpty' to TRUE. Then the input data passes validation if it is present in the input data, but has the value of an empty string.

You can specify this metacommand using the class constant Zend_Filter_Input::ALLOW_EMPTY instead of the string.

<?php
$validators 
= array(
    
'address2' => array(
        
'Alnum',
        
'allowEmpty' => true
    
)
);

The default value of this metacommand is FALSE.

In the uncommon case that you declare a validation rule with no validators, but the 'allowEmpty' metacommand is FALSE (that is, the field is considered invalid if it is empty), Zend_Filter_Input returns a default error message that you can retrieve with getMessages(). You can specify this message using the 'notEmptyMessage' option, as an argument to the Zend_Filter_Input constructor or using the setOptions() method.

<?php
$options 
= array(
    
'notEmptyMessage' => "A non-empty value is required for field '%field%'"
);

$input = new Zend_Filter_Input($filters$validators$data$options);

// alternative method:

$input = new Zend_Filter_Input($filters$validators$data);
$input->setOptions($options);

The BREAK_CHAIN metacommand

By default if a rule has more than one validator, all validators are applied to the input, and the resulting messages contain all error messages caused by the input.

Alternatively, if the value of the 'breakChainOnFailure' metacommand is TRUE, the validator chain terminates after the first validator fails. The input data is not checked against subsequent validators in the chain, so it might cause more violations even if you correct the one reported.

You can specify this metacommand using the class constant Zend_Filter_Input::BREAK_CHAIN instead of the string.

<?php
$validators 
= array(
    
'month' => array(
        
'Digits',
        new 
Zend_Validate_Between(1,12),
        new 
Zend_Validate_GreaterThan(0),
        
'breakChainOnFailure' => true
    
)
);
$input = new Zend_Filter_Input(null$validators);

The default value of this metacommand is FALSE.

The validator chain class, Zend_Validate, is more flexible with respect to breaking chain execution than Zend_Filter_Input. With the former class, you can set the option to break the chain on failure independently for each validator in the chain. With the latter class, the defined value of the 'breakChainOnFailure' metacommand for a rule applies uniformly for all validators in the rule. If you require the more flexible usage, you should create the validator chain yourself, and use it as an object in the validator rule definition:

<?php
// Create validator chain with non-uniform breakChainOnFailure
// attributes
$chain = new Zend_Validate();
$chain->addValidator(new Zend_Validate_Digits(), true);
$chain->addValidator(new Zend_Validate_Between(1,12), false);
$chain->addValidator(new Zend_Validate_GreaterThan(0), true);

// Declare validator rule using the chain defined above
$validators = array(
    
'month' => $chain
);
$input = new Zend_Filter_Input(null$validators);

The MESSAGES metacommand

You can specify error messages for each validator in a rule using the metacommand 'messages'. The value of this metacommand varies based on whether you have multiple validators in the rule, or if you want to set the message for a specific error condition in a given validator.

You can specify this metacommand using the class constant Zend_Filter_Input::MESSAGES instead of the string.

Below is a simple example of setting the default error message for a single validator.

<?php
$validators 
= array(
    
'month' => array(
        
'digits',
        
'messages' => 'A month must consist only of digits'
    
)
);

If you have multiple validators for which you want to set the error message, you should use an array for the value of the 'messages' metacommand.

Each element of this array is applied to the validator at the same index position. You can specify a message for the validator at position n by using the value n as the array index. Thus you can allow some validators to use their default message, while setting the message for a subsequent validator in the chain.

<?php
$validators 
= array(
    
'month' => array(
        
'digits',
        new 
Zend_Validate_Between(112),
        
'messages' => array(
            
// use default message for validator [0]
            // set new message for validator [1]
            
=> 'A month value must be between 1 and 12'
        
)
    )
);

If one of your validators has multiple error messages, they are identified by a message key. There are different keys in each validator class, serving as identifiers for error messages that the respective validator class might generate. Each validate class defines constants for its message keys. You can use these keys in the 'messages' metacommand by passing an associative array instead of a string.

<?php
$validators 
= array(
    
'month' => array(
        
'digits', new Zend_Validate_Between(112),
        
'messages' => array(
            
'A month must consist only of digits',
            array(
                
Zend_Validate_Between::NOT_BETWEEN =>
                    
'Month value %value% must be between ' .
                    
'%min% and %max%',
                
Zend_Validate_Between::NOT_BETWEEN_STRICT =>
                    
'Month value %value% must be strictly between ' .
                    
'%min% and %max%'
            
)
        )
    )
);

You should refer to documentation for each validator class to know if it has multiple error messages, the keys of these messages, and the tokens you can use in the message templates.

If you have only one validator in validation rule or all used validators has the same messages set, then they can be referenced without additional array construction:

<?php
$validators 
= array(
    
'month' => array(
        new 
Zend_Validate_Between(112),
        
'messages' => array(
                        
Zend_Validate_Between::NOT_BETWEEN =>
                            
'Month value %value% must be between ' .
                            
'%min% and %max%',
                        
Zend_Validate_Between::NOT_BETWEEN_STRICT =>
                            
'Month value %value% must be strictly between ' .
                            
'%min% and %max%'
        
)
    )
);

Using options to set metacommands for all rules

The default value for 'allowEmpty', 'breakChainOnFailure', and 'presence' metacommands can be set for all rules using the $options argument to the constructor of Zend_Filter_Input. This allows you to set the default value for all rules, without requiring you to set the metacommand for every rule.

<?php
// The default is set so all fields allow an empty string.
$options = array('allowEmpty' => true);

// You can override this in a rule definition,
// if a field should not accept an empty string.
$validators = array(
    
'month' => array(
        
'Digits',
        
'allowEmpty' => false
    
)
);

$input = new Zend_Filter_Input($filters$validators$data$options);

The 'fields', 'messages', and 'default' metacommands cannot be set using this technique.

Zend Framework