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

Customizing messages

Validate classes provide a setMessage() method with which you can specify the format of a message returned by getMessages() in case of validation failure. The first argument of this method is a string containing the error message. You can include tokens in this string which will be substituted with data relevant to the validator. The token %value% is supported by all validators; this is substituted with the value you passed to isValid(). Other tokens may be supported on a case-by-case basis in each validation class. For example, %max% is a token supported by Zend_Validate_LessThan. The getMessageVariables() method returns an array of variable tokens supported by the validator.

The second optional argument is a string that identifies the validation failure message template to be set, which is useful when a validation class defines more than one cause for failure. If you omit the second argument, setMessage() assumes the message you specify should be used for the first message template declared in the validation class. Many validation classes only have one error message template defined, so there is no need to specify which message template you are changing.

<?php
$validator 
= new Zend_Validate_StringLength(8);

$validator->setMessage(
    
'The string \'%value%\' is too short; it must be at least %min% ' .
    
'characters',
    
Zend_Validate_StringLength::TOO_SHORT);

if (!
$validator->isValid('word')) {
    
$messages $validator->getMessages();
    echo 
current($messages);

    
// "The string 'word' is too short; it must be at least 8 characters"
}

You can set multiple messages using the setMessages() method. Its argument is an array containing key/message pairs.

<?php
$validator 
= new Zend_Validate_StringLength(array('min' => 8'max' => 12));

$validator->setMessages( array(
    
Zend_Validate_StringLength::TOO_SHORT =>
        
'The string \'%value%\' is too short',
    
Zend_Validate_StringLength::TOO_LONG  =>
        
'The string \'%value%\' is too long'
));

If your application requires even greater flexibility with which it reports validation failures, you can access properties by the same name as the message tokens supported by a given validation class. The value property is always available in a validator; it is the value you specified as the argument of isValid(). Other properties may be supported on a case-by-case basis in each validation class.

<?php
$validator 
= new Zend_Validate_StringLength(array('min' => 8'max' => 12));

if (!
validator->isValid('word')) {
    echo 
'Word failed: '
        
$validator->value
        
'; its length is not between '
        
$validator->min
        
' and '
        
$validator->max
        
"\n";
}

Zend Framework