A free and open-source book on ZF3 for beginners


9.6. Validator Usage Examples

Next, we will consider the usage of the most important standard validators. These describe the methods (and options) a validator has, and provide a code example showing how to instantiate and apply the validator to input data.

9.6.1. Validators for Checking Value Conformance to Certain Format

In this section, we will consider usage examples of the validators from the group of validators designed for checking if input value conforms to certain format.

9.6.1.1. Ip Validator

The Ip validator class is designed to check if the input value is a valid IP address. If the input value is an IPv4 32 address, IPv6 33 address, IPvFuture 34 address, or IPv6 literal 35 address, the validator returns boolean true; otherwise it returns false. On failure, error messages can be extracted with the validator's getMessages() method.

32) An Internet Protocol version 4 (IPv4) address typically consists of four octets of the address expressed separated by periods, like "192.168.56.101".

33) An Internet Protocol version 6 (IPv6) address typically consists of eight groups of four hexadecimal digits separated by colons, such as "2001:0db8:85a3:0000:0000:8a2e:0370:7334".

34) IPvFuture is loosely defined in the Section 3.2.2 of RFC 3986.

35) A literal IPv6 address is a modification of a usual IPv6 address for using inside of a URL. (The problem with original IPv6 addresses is that the ":" and "." characters are delimiters in URLs.)

Public methods provided by the Ip validator are listed in table 9.3:

Table 9.3. Public methods of the Ip validator
Method name Description
__construct($options) Constructs the validator. Accepts the list of options.
isValid($value) Returns true if and only if value is a valid IP address.
getMessages() If validation failed, this method will return an array of error messages.
setOptions($options) Sets validator options.

The setOptions() method provides an ability to set allowed types of IP addresses:

By default all the above are allowed, except the IPv6 literal address.

Below, a code example demonstrating the usage of the Ip validator is provided.

<?php
use Zend\Validator\Ip;

// Create Ip validator.
$validator = new Ip();

// Configure the validator.
$validator->setOptions([
    'allowipv4'      => true,  // Allow IPv4 addresses.
    'allowipv6'      => true,  // Allow IPv6 addresses.
    'allowipvfuture' => false, // Allow IPvFuture addresses.
    'allowliteral'   => true,  // Allow IP addresses in literal format.
  ]);

// Check if input value is a valid IP address (IPv4).
$isValid = $validator->isValid('192.168.56.101'); // Returns true

// Check if input value is a valid IP address (IPv6).
$isValid2 = $validator->isValid(
       '2001:0db8:85a3:0000:0000:8a2e:0370:7334'); // Returns true

// Pass an invalid string (not containing an IP address).       
$isValid3 = $validator->isValid('abc'); // Returns false

9.6.1.2. Hostname Validator

The Hostname validator is designed to check if a given value is a host name belonging to set of allowed host name types. The types are:

The public methods provided by the validator are listed in table 9.4:

Table 9.4. Public methods of the Hostname validator
Method name Description
__construct($options) Constructs the validator. Accepts the list of options.
isValid($value) Returns true when the value is a valid host name; otherwise returns false.
getMessages() If validation failed, this method will return an array of error messages.
setIpValidator($ipValidator) Optionally, allows to set own IP address validator.
getIpValidator() Retrieves attached IP address validator.
setAllow() Defines the type(s) of host names which are allowed.
getAllow() Returns allowed host names types.
useIdnCheck() Defines if Internationalized Domain Names (IDN) check is enabled. This option defaults to true.
getIdnCheck() Returns true if IDN check is enabled.
useTldCheck() Defines if Top Level Domain (TLD) check is enabled. This option defaults to true.
getTldCheck() Returns true if TLD check is enabled.

You can set which host name types are allowed with the setAllow() method. It accepts a combination of the following constants:

By default, only Internet domain names are allowed.

The host name check consists of several stages, some of which may be omitted based on validator options:

  1. If the input value looks like an IP address, it is checked with the internal IP address validator. You can override which IP address validator to use for this by the setIpValidator() method.

  2. The host name is separated into domain parts (separated with dot "." character).

  3. The top-level domain is checked against the white list of available TLDs. (You can disable this check with the useTldCheck() method.)

  4. Each domain part is checked based on the rules for acceptable domain names. If a domain name is an IDN 36, it is checked against the rules for valid IDNs. (You can disable IDN check with useIdnCheck() method.)

36) An internationalized domain name (IDN) is an Internet domain name that contains at least one label that is displayed, in whole or in part, in a language-specific script or alphabet, like Arabic, Chinese or Russian.

Below, a code example demonstrating the usage of the Hostname validator is provided.

<?php
use Zend\Validator\Hostname;

// Create the Hostname validator.
$validator = new Hostname();

// Configure the validator.
$validator->setAllow(Hostname::ALLOW_DNS|Hostname::ALLOW_IP);

// Check a host name.
$isValid = $validator->isValid('site1.example.com'); 
// Returns true.
$isValid2 = $validator->isValid('abc'); 
// Returns false (not a valid host name).

9.6.1.3. Uri Validator

The Uri validator is designed to check whether the input value is a Uniform Resource Identifier (URI) 37. On failure, error messages can be extracted with the validator's getMessages() method.

Don't be confused with the term URI. In most cases, you may think of URI as of a usual URL.

37) A Uniform Resource Identifier (URI) is a compact sequence of characters that identifies an abstract or physical resource. An Uniform Resource Locator (URL) is a type of URI. But, that doesn't mean all URIs are URLs.

The public methods provided by the Uri validator are listed in table 9.5:

Table 9.5. Public methods of the Uri validator
Method name Description
__construct($options) Constructs the validator. Accepts the list of options.
isValid($value) Returns true when the value is a valid URI; otherwise returns false.
getMessages() If validation failed, this method will return an array of error messages.
setUriHandler($uriHandler) Sets the URI handler object for this validator.
getUriHandler() Retrieves the URI handler object.
setAllowAbsolute($allowAbsolute) Tells the validator whether absolute URIs are accepted.
getAllowAbsolute() Returns true if absolute URIs are accepted.
setAllowRelative($allowRelative) Tells the validator whether relative URIs are accepted.
getAllowRelative() Returns true if relative URIs are accepted.

Internally, the Uri validator uses so called URI handler object, which is responsible for parsing an URI string. By default, Zend\Uri\Uri class is used as the URI handler. (You can set your custom URI handler with the setUriHandler() method, if you wish.)

An URI can be absolute or relative. For example, an absolute URI is "http://example.com/blog/2014/02/02/edit", while a relative URI is "2014/02/02/edit". You can specify whether the validator should consider absolute and/or relative URIs acceptable. For that, you use the setAllowAbsolute() and setAllowRelative() methods, respectively. By default, both are treated as acceptable URI types.

Below, a code example demonstrating the usage of the Uri validator is provided.

<?php
use Zend\Validator\Uri;

// Create the Uri validator.
$validator = new Uri();

// Configure the validator.
$validator->setAllowAbsolute(true);
$validator->setAllowRelative(true);

// Check an URI.
$isValid = $validator->isValid('http://site1.example.com/application/index/index'); 
// Returns true.
$isValid2 = $validator->isValid('index/index'); 
// Returns true.

9.6.1.4. Date Validator

The Date validator is intended for checking whether the input data is a date in a given format. On failure, error messages can be extracted with the validator's getMessages() method.

Public methods provided by the Date validator are listed in table 9.6:

Table 9.6. Public methods of the Date validator
Method name Description
__construct($options) Constructs the validator. Accepts the list of options.
isValid($value) Returns true when the value is a string containing a date in expected format; otherwise returns false.
getMessages() If validation failed, this method will return an array of error messages.
setFormat($format) Sets an acceptable date format.
getFormat() Retrieves the expected format.

To set the expected date format, you can use the setFormat() method.

Internally, the DateTimeFormatter filter uses the DateTime class from the PHP standard library for converting and formatting dates. For available date formats, please refer to the PHP documentation for the DateTime class.

Below, a code example demonstrating the usage of the Date validator is provided.

<?php
use Zend\Validator\Date;

// Create validator instance.
$validator = new Date();

// Configure validator.
$validator->setFormat('Y-m-d');

// Check if the input value is a date having expected format.
$isValid = $validator->isValid('2014-04-04'); // Returns true.
$isValid2 = $validator->isValid('April 04, 2014'); // Returns false (format is unexpected).

9.6.1.5. Regex Validator

This validator allows you to validate if a given string conforms some regular expression. It returns true if the string matches the regular expression, otherwise it returns false. On failure, error messages can be extracted with the validator's getMessages() method.

The public methods provided by the Regex validator are listed in table 9.7:

Table 9.7. Public methods of the Regex validator
Method name Description
__construct($options) Constructs the validator. Accepts the list of options.
isValid($value) Returns true if and only if $value matches the given regular expression pattern.
getMessages() If validation failed, this method will return an array of error messages.
setPattern($pattern) Sets the regular expression pattern.
getPattern() Retrieves the regular expression pattern.

The setPattern() method allows to set the regular expression to match against.

For regular expressions syntax and examples, it is recommended that your refer to the PCRE Patterns section of the PHP documentation.

Below, a code example demonstrating the usage of the Regex validator is provided. It uses the regular expression to check if the input string is a valid IPv4 address (such address typically consists of four groups of digits separated with dots).

<?php
use Zend\Validator\Regex;

// Create Regex validator.
$validator = new Regex();

// Set regular expression to check for an IP address.
$validator->setPattern('\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b');

// Check for regular expression match.
$isValid = $validator->isValid("127.0.0.1"); // returns true.
$isValid2 = $validator->isValid("123"); // returns false.

9.6.2. Validators for Checking if a Numerical Value Lies in a Given Range

In this section, we will consider usage examples of the validators from the group of validators designed for checking if input value lies in a given range.

9.6.2.1. NotEmpty Validator

The NotEmpty validator allows to check if input value is not empty. This is often useful when working with form elements or other user input, where you can use it to ensure required elements have values associated with them.

The public methods provided by the NotEmpty validator are listed in table 9.8:

Table 9.8. Public methods of the NotEmpty validator
Method name Description
__construct($options) Constructs the validator. Accepts the list of options.
isValid($value) Returns true if and only if $value is not an empty value.
getMessages() If validation failed, this method will return an array of error messages.
setType($type) Set the value types that to consider as empty values.
getType() Returns the types.
getDefaultType() Returns the default types.

The setType() method specifies which variable types to consider as an empty value. This method accepts the single argument $type which can be either an OR combination of the constants listed in table 9.9, or an array containing the literal equivalents of those constants.

Table 9.9. Type constants
Constant Numeric Value Literal Equivalent Description
BOOLEAN 1 "boolean" Consider boolean false as an empty value.
INTEGER 2 "integer" Consider integer 0 as an empty value.
FLOAT 4 "float" Consider float 0.0 as an empty value.
STRING 8 "string" Consider empty string '' as an empty value.
ZERO 16 "zero" Consider string containing the single character zero ('0') as an empty value.
EMPTY_ARRAY 32 "array" Consider an empty array as an empty value.
NULL 64 "null" Consider null as an empty value.
PHP 127 "php" Consider the value empty if the empty() PHP function would return true on it.
SPACE 128 "space" Consider a string which contains only white spaces as an empty value.
OBJECT 256 "object" Returns true. false will be returned when object is not allowed but an object is given.
OBJECT_STRING 512 "objectstring" Returns false when an object is given and it's __toString() method returns an empty string.
OBJECT_COUNT 1024 "objectcount" Returns false when an object is given, it has an Countable interface and it's count is 0.
ALL 2047 "all" Consider all above types as empty values.

Below, a code example demonstrating the usage of the NotEmpty validator is provided.

<?php
use Zend\Validator\NotEmpty;

// Create validator instance.
$validator = new NotEmpty();

// Configure validator.
$validator->setType(NotEmpty::ALL);

// Check if input value not empty.
$isValid1 = $validator->isValid('some string'); // returns true
$isValid2 = $validator->isValid(''); // returns false 
$isValid3 = $validator->isValid(0); // returns false

9.6.2.2. Between Validator

The Between validator checks whether a number lies in a certain range (min, max), either inclusively (by default) or exclusively.

The public methods provided by the Between validator are listed in table 9.10:

Table 9.10. Public methods of the Between validator
Method name Description
__construct($options) Constructs the validator. Accepts the list of options.
isValid($value) Returns true if and only if value's length is within the given range.
getMessages() If validation failed, this method will return an array of error messages.
setMin($min) Sets the minimum limit.
getMin() Retrieves the minimum limit.
setMax($max) Sets the maximum limit.
getMax() Retrieves the maximum limit.
setInclusive($inclusive) Sets whether to compare if the value lies in the given boundaries inclusively.
getInclusive() Returns the inclusive option.

The range can be set with the setMin() and setMax() methods.

By default, the validator performs inclusive comparisons (to check if the value belongs to the given range, it compares if the value is greater or equal to its lower bound, and if the value is lower or equal to its upper bound). You can change this with the setInclusive() method. It tells the validator whether to perform inclusive comparisons (pass true as the argument) or exclusive comparisons (pass false as the argument).

Below, a code example demonstrating the usage of the Between validator is provided.

<?php
use Zend\Validator\Between;

// Create validator instance.
$validator = new Between();

// Configure validator.
$validator->setMin(1);
$validator->setMax(10);
$validator->setInclusive(true);

$isValid1 = $validator->isValid(5); // returns true.
$isValid2 = $validator->isValid(10); // returns true.
$isValid3 = $validator->isValid(0); // returns false (value is too small).
$isValid4 = $validator->isValid(15); // returns false (value is too big).

9.6.2.3. InArray Validator

The InArray validator checks whether the input value belongs to the given array of values. The public methods provided by the InArray validator are listed in table 9.11:

Table 9.11. Public methods of the InArray validator
Method name Description
__construct($options) Constructs the validator. Accepts the list of options.
isValid($value) Returns true if and only if value belongs to the given array.
getMessages() If validation failed, this method will return an array of error messages.
setHaystack($haystack) Sets the array to search in.
getHaystack() Returns the array of allowed values.
setStrict($strict) Sets strict comparison mode.
getStrict() Whether strict comparison mode enabled?
setRecursive($recursive) Tells the validator to search recursively.
getRecursive() Whether the recursive search is enabled?

The setHaystack() method allows to set the array of allowed values. The isValid() method will search through this array for the presence of the input $value.

If the array contains nested values and you want to search among them recursively, then use setRecursive() method. This method takes the single boolean flag. If the flag is true, than the search will be performed recursively; otherwise the nested levels will be ignored.

The setStrict() method provides an ability to tell the validator how to compare the input value and the values in array. This may be a combination of the following constants:

Below, a code example demonstrating the usage of the InArray validator is provided.

<?php
use Zend\Validator\InArray;

// Create validator instance.
$validator = new InArray();

// Configure validator.
$validator->setHaystack([1, 3, 5]);

// Perform validation.
$isValid1 = $validator->isValid(1); // returns true.
$isValid2 = $validator->isValid(2); // returns false.

9.6.2.4. StringLength Validator

The StringLength validator checks whether the input string length belongs to the given range, inclusively. It returns true if and only if the string length of value is at least the min option and no greater than the max option (when the max option is not null).

The public methods provided by the StringLength validator are listed in table 9.12:

Table 9.12. Public methods of the StringLength validator
Method name Description
__construct($options) Constructs the validator. Accepts the list of options.
isValid($value) Returns true if and only if value's length is within the given range.
getMessages() If validation failed, this method will return an array of error messages.
setMin($min) Sets the minimum limit.
getMin() Retrieves the minimum limit.
setMax($max) Sets the maximum limit.
getMax() Retrieves the maximum limit.
setEncoding($encoding) Sets a new encoding to use.
getEncoding() Retrieves the encoding.

By default, the StringLength validator considers any string length as valid. Use the setMin() and/or setMax() methods to set lower and upper limits for the allowable string length. There are three possible ways you can do that:

By default, the PHP engine uses the UTF-8 encoding for strings. If your input string uses a different encoding, you should specify it encoding with the setEncoding() validator's method.

Below, a code example demonstrating the usage of the StringLength validator is provided.

<?php
use Zend\Validator\StringLength;

// Create validator instance.
$validator = new StringLength();

// Configure the validator.
$validator->setMin(1);
$validator->setMax(10);

$isValid1 = $validator->isValid("string"); // returns true.
$isValid2 = $validator->isValid(""); // returns false (value is too short).
$isValid3 = $validator->isValid("a very long string"); // returns false (value is too long).

9.6.3. Organizing Validators in a Chain

Validators can be organized in a sequence. This is accomplished by the ValidatorChain class. When such a compound validator is run, the input value is passed to all validators in turn. The ValidatorChain validator's isValid() method returns true if all validators in the chain return true; otherwise it returns false.

The ValidatorChain class is internally used by the InputFilter container class for storing the sequence of validators attached to a form model's field.

Public methods provided by the ValidatorChain class are presented in table 9.13:

Table 9.13. Public methods of the ValidatorChain validator
Method name Description
isValid($value) Returns true if all validators in the chain return true.
getMessages() Returns the array of validation error messages.
getValidators() Returns the array of validators in the chain.
count() Returns count of validators in the chain.
attach($validator, $breakChainOnFailure) Attaches a validator to the end of the chain.
prependValidator($validator, $breakChainOnFailure) Adds a validator to the beginning of the chain.
attachByName($name, $options, $breakChainOnFailure) Use the plugin manager to add a validator by name.
prependByName($name, $options, $breakChainOnFailure) Use the plugin manager to prepend a validator by name.
merge($validatorChain) Merge the validator chain with the one given in parameter.

An example validator chain is shown in figure 9.2. It consists of the NotEmpty validator followed by the StringLength validator, which in turn is followed by the Date validator. When this chain is executed, first, the NotEmpty validator is run checking that the value is a non-empty value, then the StringLength validator is run checking that the length of the input string belongs to range (1, 16), inclusively, and finally, the Date validator is run checking that the input value is a date in format "YYYY-MM-DD".

Figure 9.2. Validator chain Figure 9.2. Validator chain

To construct the filter chain like in figure 9.2, we can use the following code:

<?php
// Instantiate the validator chain.
$validator = new \Zend\Validator\ValidatorChain();

// Insert validators into validator chain.
$validator->attachByName('NotEmpty');
$validator->attachByName('StringLength', ['min'=>1, 'max'=>16]);
$validator->attachByName('Date', ['format'=>'Y-m-d']);

// Execute all validators in the chain.
$isValid = $validator->isValid('2014-04-04'); // Returns true.

9.6.4. Custom Validation with the Callback Validator

The Callback validator can be a wrapper for your custom validation algorithm. For example, this may be useful when a standard validator is not suitable, and you need to apply your own checking algorithm to the data. The public methods provided by the Callback validator are listed in table 9.14.

Table 9.14. Public methods of the Callback validator
Class name Description
isValid($value, $context) Executes a callback function as a validator.
getMessages() If validation failed, this method will return an array of error messages.
setCallback($callback) Sets a new callback for this filter.
getCallback() Returns callback set for the filter.
setCallbackOptions($options) Sets options for the callback.
getCallbackOptions() Get parameters for the callback.

As you can see from the table, the Callback validator provides the setCallback() and setCallbackOptions() methods that can be used to set the callback function or class method and (optionally) pass it one or several parameters.

9.6.4.1. Example

To demonstrate the usage of the Callback validator, let's add the phone number validator to our ContactForm form model class. The validator would check a telephone number entered by site visitor.

The validator needs to be able to check for two common phone number formats:

Because ZF3 does not provide a standard validator for accomplishing such phone filtering operation, we will use the Callback wrapper validator. To do that, we will make the following changes to the code of our ContactForm class:

<?php
// ...
class ContactForm extends Form
{    
  // ..
  protected function addElements() {
    // ...
	
    // Add "phone" field
    $this->add([
        'type'  => 'text',
        'name' => 'phone',
        'attributes' => [                
          'id' => 'phone'
        ],
        'options' => [
          'label' => 'Your Phone',
        ],
      ]);
  }
    
  private function addInputFilter() 
  {
    // ...
        
    $inputFilter->add([
            'name'     => 'phone',
            'required' => true,                
            'validators' => [
                [
                  'name' => 'Callback',
                  'options' => [
                     'callback' => [$this, 'validatePhone'],
                     'callbackOptions' => [
                     'format' => 'intl'
                  ]
                ]                        
              ]                    
            ]
        );
  }
        
  // Custom validator for a phone number.
  public function validatePhone($value, $context, $format) 
  {
    // Determine the correct length and pattern of the phone number,
    // depending on the format.
    if($format == 'intl') {
      $correctLength = 16;
      $pattern = '/^\d\ (\d{3}\) \d{3}-\d{4}$/';
    } else { // 'local'
      $correctLength = 8;
      $pattern = '/^\d{3}-\d{4}$/';
    }
                
    // Check phone number length.
    if(strlen($value)!=$correctLength)
      return false;

    // Check if the value matches the pattern.
    $matchCount = preg_match($pattern, $value);
        
    return ($matchCount!=0)?true:false;
  }
}

In the code above, we create the phone field in our ContactForm (if you already have such field, just ignore this).

In lines 26-40, we add the Callback validator to the input filter's validator chain for the "phone" field.

In lines 44-64, we have the validatePhone() callback method. The method accepts three arguments: the $value parameter is the phone number to validate, the $context parameter receives the values of every field of the form (it may be needed for some validators to refer to the values of other form fields, too); and the $format parameter is the expected format of the phone number ("intl" or "local").

Inside of the callback method, we do the following:

  1. Calculate the correct length of the phone, check whether the length is correct for the selected phone number format.
  2. Match the phone number against the regular expression pattern for the selected phone format.

Top