Documentation

Writing Validators - Zend_Validate

Writing Validators

Zend_Validate supplies a set of commonly needed validators, but inevitably, developers will wish to write custom validators for their particular needs. The task of writing a custom validator is described in this section.

Zend_Validate_Interface defines two methods, isValid() and getMessages(), that may be implemented by user classes in order to create custom validation objects. An object that implements Zend_Validate_Interface interface may be added to a validator chain with Zend_Validate::addValidator(). Such objects may also be used with Zend_Filter_Input.

As you may already have inferred from the above description of Zend_Validate_Interface, validation classes provided with Zend Framework return a boolean value for whether or not a value validates successfully. They also provide information about why a value failed validation. The availability of the reasons for validation failures may be valuable to an application for various purposes, such as providing statistics for usability analysis.

Basic validation failure message functionality is implemented in Zend_Validate_Abstract. To include this functionality when creating a validation class, simply extend Zend_Validate_Abstract. In the extending class you would implement the isValid() method logic and define the message variables and message templates that correspond to the types of validation failures that can occur. If a value fails your validation tests, then isValid() should return FALSE. If the value passes your validation tests, then isValid() should return TRUE.

In general, the isValid() method should not throw any exceptions, except where it is impossible to determine whether or not the input value is valid. A few examples of reasonable cases for throwing an exception might be if a file cannot be opened, an LDAP server could not be contacted, or a database connection is unavailable, where such a thing may be required for validation success or failure to be determined.

Example #1 Creating a Simple Validation Class

The following example demonstrates how a very simple custom validator might be written. In this case the validation rules are simply that the input value must be a floating point value.

  1. class MyValid_Float extends Zend_Validate_Abstract
  2. {
  3.     const FLOAT = 'float';
  4.  
  5.     protected $_messageTemplates = array(
  6.         self::FLOAT => "'%value%' is not a floating point value"
  7.     );
  8.  
  9.     public function isValid($value)
  10.     {
  11.         $this->_setValue($value);
  12.  
  13.         if (!is_float($value)) {
  14.             $this->_error(self::FLOAT);
  15.             return false;
  16.         }
  17.  
  18.         return true;
  19.     }
  20. }

The class defines a template for its single validation failure message, which includes the built-in magic parameter, %value%. The call to _setValue() prepares the object to insert the tested value into the failure message automatically, should the value fail validation. The call to _error() tracks a reason for validation failure.

Example #2 Writing a Validation Class having Dependent Conditions

The following example demonstrates a more complex set of validation rules, where it is required that the input value be numeric and within the range of minimum and maximum boundary values. An input value would fail validation for exactly one of the following reasons:

  • The input value is not numeric.

  • The input value is less than the minimum allowed value.

  • The input value is more than the maximum allowed value.

These validation failure reasons are then translated to definitions in the class:

  1. class MyValid_NumericBetween extends Zend_Validate_Abstract
  2. {
  3.     const MSG_NUMERIC = 'msgNumeric';
  4.     const MSG_MINIMUM = 'msgMinimum';
  5.     const MSG_MAXIMUM = 'msgMaximum';
  6.  
  7.     public $minimum = 0;
  8.     public $maximum = 100;
  9.  
  10.     protected $_messageVariables = array(
  11.         'min' => 'minimum',
  12.         'max' => 'maximum'
  13.     );
  14.  
  15.     protected $_messageTemplates = array(
  16.         self::MSG_NUMERIC => "'%value%' is not numeric",
  17.         self::MSG_MINIMUM => "'%value%' must be at least '%min%'",
  18.         self::MSG_MAXIMUM => "'%value%' must be no more than '%max%'"
  19.     );
  20.  
  21.     public function isValid($value)
  22.     {
  23.         $this->_setValue($value);
  24.  
  25.         if (!is_numeric($value)) {
  26.             $this->_error(self::MSG_NUMERIC);
  27.             return false;
  28.         }
  29.  
  30.         if ($value < $this->minimum) {
  31.             $this->_error(self::MSG_MINIMUM);
  32.             return false;
  33.         }
  34.  
  35.         if ($value > $this->maximum) {
  36.             $this->_error(self::MSG_MAXIMUM);
  37.             return false;
  38.         }
  39.  
  40.         return true;
  41.     }
  42. }

The public properties $minimum and $maximum have been established to provide the minimum and maximum boundaries, respectively, for a value to successfully validate. The class also defines two message variables that correspond to the public properties and allow min and max to be used in message templates as magic parameters, just as with value.

Note that if any one of the validation checks in isValid() fails, an appropriate failure message is prepared, and the method immediately returns FALSE. These validation rules are therefore sequentially dependent. That is, if one test should fail, there is no need to test any subsequent validation rules. This need not be the case, however. The following example illustrates how to write a class having independent validation rules, where the validation object may return multiple reasons why a particular validation attempt failed.

Example #3 Validation with Independent Conditions, Multiple Reasons for Failure

Consider writing a validation class for password strength enforcement - when a user is required to choose a password that meets certain criteria for helping secure user accounts. Let us assume that the password security criteria enforce that the password:

  • is at least 8 characters in length,

  • contains at least one uppercase letter,

  • contains at least one lowercase letter,

  • and contains at least one digit character.

The following class implements these validation criteria:

  1. class MyValid_PasswordStrength extends Zend_Validate_Abstract
  2. {
  3.     const LENGTH = 'length';
  4.     const UPPER  = 'upper';
  5.     const LOWER  = 'lower';
  6.     const DIGIT  = 'digit';
  7.  
  8.     protected $_messageTemplates = array(
  9.         self::LENGTH => "'%value%' must be at least 8 characters in length",
  10.         self::UPPER  => "'%value%' must contain at least one uppercase letter",
  11.         self::LOWER  => "'%value%' must contain at least one lowercase letter",
  12.         self::DIGIT  => "'%value%' must contain at least one digit character"
  13.     );
  14.  
  15.     public function isValid($value)
  16.     {
  17.         $this->_setValue($value);
  18.  
  19.         $isValid = true;
  20.  
  21.         if (strlen($value) < 8) {
  22.             $this->_error(self::LENGTH);
  23.             $isValid = false;
  24.         }
  25.  
  26.         if (!preg_match('/[A-Z]/', $value)) {
  27.             $this->_error(self::UPPER);
  28.             $isValid = false;
  29.         }
  30.  
  31.         if (!preg_match('/[a-z]/', $value)) {
  32.             $this->_error(self::LOWER);
  33.             $isValid = false;
  34.         }
  35.  
  36.         if (!preg_match('/\d/', $value)) {
  37.             $this->_error(self::DIGIT);
  38.             $isValid = false;
  39.         }
  40.  
  41.         return $isValid;
  42.     }
  43. }

Note that the four criteria tests in isValid() do not immediately return FALSE. This allows the validation class to provide all of the reasons that the input password failed to meet the validation requirements. if, for example, a user were to input the string "#$%" as a password, isValid() would cause all four validation failure messages to be returned by a subsequent call to getMessages().

Copyright

© 2006-2021 by Zend by Perforce. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.

Contacts