Standard Validation Classes

Zend Framework comes with a standard set of validation classes, which are ready for you to use.

Alnum

Zend\I18n\Validator\Alnum allows you to validate if a given value contains only alphabetical characters and digits. There is no length limitation for the input you want to validate.

Supported options for ZendI18nValidatorAlnum

The following options are supported for Zend\I18n\Validator\Alnum:

  • allowWhiteSpace: If whitespace characters are allowed. This option defaults to FALSE

Basic usage

A basic example is the following one:

1
2
3
4
5
6
$validator = new Zend\Validator\Alnum();
if ($validator->isValid('Abcd12')) {
    // value contains only allowed chars
} else {
    // false
}

Using whitespaces

Per default whitespaces are not accepted because they are not part of the alphabet. Still, there is a way to accept them as input. This allows to validate complete sentences or phrases.

To allow the usage of whitespaces you need to give the allowWhiteSpace option. This can be done while creating an instance of the validator, or afterwards by using setAllowWhiteSpace(). To get the actual state you can use getAllowWhiteSpace().

1
2
3
4
5
6
$validator = new Zend\Validator\Alnum(array('allowWhiteSpace' => true));
if ($validator->isValid('Abcd and 12')) {
    // value contains only allowed chars
} else {
    // false
}

Using different languages

When using Zend\I18n\Validator\Alnum then the language which the user sets within his browser will be used to set the allowed characters. This means when your user sets de for german then he can also enter characters like ä, ö and ü additionally to the characters from the english alphabet.

Which characters are allowed depends completely on the used language as every language defines it’s own set of characters.

There are actually 3 languages which are not accepted in their own script. These languages are korean, japanese and chinese because this languages are using an alphabet where a single character is build by using multiple characters.

In the case you are using these languages, the input will only be validated by using the english alphabet.

Alpha

Zend\Validator\Alpha allows you to validate if a given value contains only alphabetical characters. There is no length limitation for the input you want to validate. This validator is related to the Zend\Validator\Alnum validator with the exception that it does not accept digits.

Supported options for Zend\Validator\Alpha

The following options are supported for Zend\Validator\Alpha:

  • allowWhiteSpace: If whitespace characters are allowed. This option defaults to FALSE

Basic usage

A basic example is the following one:

1
2
3
4
5
6
$validator = new Zend\Validator\Alpha();
if ($validator->isValid('Abcd')) {
    // value contains only allowed chars
} else {
    // false
}

Using whitespaces

Per default whitespaces are not accepted because they are not part of the alphabet. Still, there is a way to accept them as input. This allows to validate complete sentences or phrases.

To allow the usage of whitespaces you need to give the allowWhiteSpace option. This can be done while creating an instance of the validator, or afterwards by using setAllowWhiteSpace(). To get the actual state you can use getAllowWhiteSpace().

1
2
3
4
5
6
$validator = new Zend\Validator\Alpha(array('allowWhiteSpace' => true));
if ($validator->isValid('Abcd and efg')) {
    // value contains only allowed chars
} else {
    // false
}

Using different languages

When using Zend\Validator\Alpha then the language which the user sets within his browser will be used to set the allowed characters. This means when your user sets de for german then he can also enter characters like ä, ö and ü additionally to the characters from the english alphabet.

Which characters are allowed depends completely on the used language as every language defines it’s own set of characters.

There are actually 3 languages which are not accepted in their own script. These languages are korean, japanese and chinese because this languages are using an alphabet where a single character is build by using multiple characters.

In the case you are using these languages, the input will only be validated by using the english alphabet.

Barcode

Zend\Validator\Barcode allows you to check if a given value can be represented as barcode.

Zend\Validator\Barcode supports multiple barcode standards and can be extended with proprietary barcode implementations very easily. The following barcode standards are supported:

  • CODABAR: Also known as Code-a-bar.

    This barcode has no length limitation. It supports only digits, and 6 special chars. Codabar is a self-checking barcode. This standard is very old. Common use cases are within airbills or photo labs where multi-part forms are used with dot-matrix printers.

  • CODE128: CODE128 is a high density barcode.

    This barcode has no length limitation. It supports the first 128 ascii characters. When used with printing characters it has an checksum which is calculated modulo 103. This standard is used worldwide as it supports upper and lowercase characters.

  • CODE25: Often called “two of five” or “Code25 Industrial”.

    This barcode has no length limitation. It supports only digits, and the last digit can be an optional checksum which is calculated with modulo 10. This standard is very old and nowadays not often used. Common use cases are within the industry.

  • CODE25INTERLEAVED: Often called “Code 2 of 5 Interleaved”.

    This standard is a variant of CODE25. It has no length limitation, but it must contain an even amount of characters. It supports only digits, and the last digit can be an optional checksum which is calculated with modulo 10. It is used worldwide and common on the market.

  • CODE39: CODE39 is one of the oldest available codes.

    This barcode has a variable length. It supports digits, upper cased alphabetical characters and 7 special characters like whitespace, point and dollar sign. It can have an optional checksum which is calculated with modulo 43. This standard is used worldwide and common within the industry.

  • CODE39EXT: CODE39EXT is an extension of CODE39.

    This barcode has the same properties as CODE39. Additionally it allows the usage of all 128 ASCII characters. This standard is used worldwide and common within the industry.

  • CODE93: CODE93 is the successor of CODE39.

    This barcode has a variable length. It supports digits, alphabetical characters and 7 special characters. It has an optional checksum which is calculated with modulo 47 and contains 2 characters. This standard produces a denser code than CODE39 and is more secure.

  • CODE93EXT: CODE93EXT is an extension of CODE93.

    This barcode has the same properties as CODE93. Additionally it allows the usage of all 128 ASCII characters. This standard is used worldwide and common within the industry.

  • EAN2: EAN is the shortcut for “European Article Number”.

    These barcode must have 2 characters. It supports only digits and does not have a checksum. This standard is mainly used as addition to EAN13 (ISBN) when printed on books.

  • EAN5: EAN is the shortcut for “European Article Number”.

    These barcode must have 5 characters. It supports only digits and does not have a checksum. This standard is mainly used as addition to EAN13 (ISBN) when printed on books.

  • EAN8: EAN is the shortcut for “European Article Number”.

    These barcode can have 7 or 8 characters. It supports only digits. When it has a length of 8 characters it includes a checksum. This standard is used worldwide but has a very limited range. It can be found on small articles where a longer barcode could not be printed.

  • EAN12: EAN is the shortcut for “European Article Number”.

    This barcode must have a length of 12 characters. It supports only digits, and the last digit is always a checksum which is calculated with modulo 10. This standard is used within the USA and common on the market. It has been superseded by EAN13.

  • EAN13: EAN is the shortcut for “European Article Number”.

    This barcode must have a length of 13 characters. It supports only digits, and the last digit is always a checksum which is calculated with modulo 10. This standard is used worldwide and common on the market.

  • EAN14: EAN is the shortcut for “European Article Number”.

    This barcode must have a length of 14 characters. It supports only digits, and the last digit is always a checksum which is calculated with modulo 10. This standard is used worldwide and common on the market. It is the successor for EAN13.

  • EAN18: EAN is the shortcut for “European Article Number”.

    This barcode must have a length of 18 characters. It support only digits. The last digit is always a checksum digit which is calculated with modulo 10. This code is often used for the identification of shipping containers.

  • GTIN12: GTIN is the shortcut for “Global Trade Item Number”.

    This barcode uses the same standard as EAN12 and is its successor. It’s commonly used within the USA.

  • GTIN13: GTIN is the shortcut for “Global Trade Item Number”.

    This barcode uses the same standard as EAN13 and is its successor. It is used worldwide by industry.

  • GTIN14: GTIN is the shortcut for “Global Trade Item Number”.

    This barcode uses the same standard as EAN14 and is its successor. It is used worldwide and common on the market.

  • IDENTCODE: Identcode is used by Deutsche Post and DHL. It’s an specialized implementation of Code25.

    This barcode must have a length of 12 characters. It supports only digits, and the last digit is always a checksum which is calculated with modulo 10. This standard is mainly used by the companies DP and DHL.

  • INTELLIGENTMAIL: Intelligent Mail is a postal barcode.

    This barcode can have a length of 20, 25, 29 or 31 characters. It supports only digits, and contains no checksum. This standard is the successor of PLANET and POSTNET. It is mainly used by the United States Postal Services.

  • ISSN: ISSN is the abbreviation for International Standard Serial Number.

    This barcode can have a length of 8 or 13 characters. It supports only digits, and the last digit must be a checksum digit which is calculated with modulo 11. It is used worldwide for printed publications.

  • ITF14: ITF14 is the GS1 implementation of an Interleaved Two of Five bar code.

    This barcode is a special variant of Interleaved 2 of 5. It must have a length of 14 characters and is based on GTIN14. It supports only digits, and the last digit must be a checksum digit which is calculated with modulo 10. It is used worldwide and common within the market.

  • LEITCODE: Leitcode is used by Deutsche Post and DHL. It’s an specialized implementation of Code25.

    This barcode must have a length of 14 characters. It supports only digits, and the last digit is always a checksum which is calculated with modulo 10. This standard is mainly used by the companies DP and DHL.

  • PLANET: Planet is the abbreviation for Postal Alpha Numeric Encoding Technique.

    This barcode can have a length of 12 or 14 characters. It supports only digits, and the last digit is always a checksum. This standard is mainly used by the United States Postal Services.

  • POSTNET: Postnet is used by the US Postal Service.

    This barcode can have a length of 6, 7, 10 or 12 characters. It supports only digits, and the last digit is always a checksum. This standard is mainly used by the United States Postal Services.

  • ROYALMAIL: Royalmail is used by Royal Mail.

    This barcode has no defined length. It supports digits, uppercase letters, and the last digit is always a checksum. This standard is mainly used by Royal Mail for their Cleanmail Service. It is also called RM4SCC.

  • SSCC: SSCC is the shortcut for “Serial Shipping Container Code”.

    This barcode is a variant of EAN barcode. It must have a length of 18 characters and supports only digits. The last digit must be a checksum digit which is calculated with modulo 10. It is commonly used by the transport industry.

  • UPCA: UPC is the shortcut for “Universal Product Code”.

    This barcode preceded EAN13. It must have a length of 12 characters and supports only digits. The last digit must be a checksum digit which is calculated with modulo 10. It is commonly used within the USA.

  • UPCE: UPCE is the short variant from UPCA.

    This barcode is a smaller variant of UPCA. It can have a length of 6, 7 or 8 characters and supports only digits. When the barcode is 8 chars long it includes a checksum which is calculated with modulo 10. It is commonly used with small products where a UPCA barcode would not fit.

Supported options for Zend\Validator\Barcode

The following options are supported for Zend\Validator\Barcode:

  • adapter: Sets the barcode adapter which will be used. Supported are all above noted adapters. When using a self defined adapter, then you have to set the complete class name.
  • checksum: TRUE when the barcode should contain a checksum. The default value depends on the used adapter. Note that some adapters don’t allow to set this option.
  • options: Defines optional options for a self written adapters.

Basic usage

To validate if a given string is a barcode you just need to know its type. See the following example for an EAN13 barcode:

1
2
3
4
5
6
$valid = new Zend\Validator\Barcode('EAN13');
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Optional checksum

Some barcodes can be provided with an optional checksum. These barcodes would be valid even without checksum. Still, when you provide a checksum, then you should also validate it. By default, these barcode types perform no checksum validation. By using the checksum option you can define if the checksum will be validated or ignored.

1
2
3
4
5
6
7
8
9
$valid = new Zend\Validator\Barcode(array(
    'adapter'  => 'EAN13',
    'checksum' => false,
));
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Note

Reduced security by disabling checksum validation

By switching off checksum validation you will also reduce the security of the used barcodes. Additionally you should note that you can also turn off the checksum validation for those barcode types which must contain a checksum value. Barcodes which would not be valid could then be returned as valid even if they are not.

Writing custom adapters

You may write custom barcode validators for usage with Zend\Validator\Barcode; this is often necessary when dealing with proprietary barcode types. To write your own barcode validator, you need the following information.

  • Length: The length your barcode must have. It can have one of the following values:
    • Integer: A value greater 0, which means that the barcode must have this length.
    • -1: There is no limitation for the length of this barcode.
    • “even”: The length of this barcode must have a even amount of digits.
    • “odd”: The length of this barcode must have a odd amount of digits.
    • array: An array of integer values. The length of this barcode must have one of the set array values.
  • Characters: A string which contains all allowed characters for this barcode. Also the integer value 128 is allowed, which means the first 128 characters of the ASCII table.
  • Checksum: A string which will be used as callback for a method which does the checksum validation.

Your custom barcode validator must extend Zend\Validator\Barcode\AbstractAdapter or implement Zend\Validator\Barcode\AdapterInterface.

As an example, let’s create a validator that expects an even number of characters that include all digits and the letters ‘ABCDE’, and which requires a checksum.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class My\Barcode\MyBar extends Zend\Validator\Barcode\AbstractAdapter
{
    protected $length     = 'even';
    protected $characters = '0123456789ABCDE';
    protected $checksum   = 'mod66';

    protected function mod66($barcode)
    {
        // do some validations and return a boolean
    }
}

$valid = new Zend\Validator\Barcode('My\Barcode\MyBar');
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Between

Zend\Validator\Between allows you to validate if a given value is between two other values.

Note

Zend\Validator\Between supports only number validation

It should be noted that Zend\Validator\Between supports only the validation of numbers. Strings or dates can not be validated with this validator.

Supported options for Zend\Validator\Between

The following options are supported for Zend\Validator\Between:

  • inclusive: Defines if the validation is inclusive the minimum and maximum border values or exclusive. It defaults to TRUE.
  • max: Sets the maximum border for the validation.
  • min: Sets the minimum border for the validation.

Default behaviour for Zend\Validator\Between

Per default this validator checks if a value is between min and max where both border values are allowed as value.

1
2
3
4
$valid  = new Zend\Validator\Between(array('min' => 0, 'max' => 10));
$value  = 10;
$result = $valid->isValid($value);
// returns true

In the above example the result is TRUE due to the reason that per default the search is inclusively the border values. This means in our case that any value from ‘0’ to ‘10’ is allowed. And values like ‘-1’ and ‘11’ will return FALSE.

Validation exclusive the border values

Sometimes it is useful to validate a value by excluding the border values. See the following example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$valid  = new Zend\Validator\Between(
    array(
        'min' => 0,
        'max' => 10,
        'inclusive' => false
    )
);
$value  = 10;
$result = $valid->isValid($value);
// returns false

The example is almost equal to our first example but we excluded the border value. Now the values ‘0’ and ‘10’ are no longer allowed and will return FALSE.

Callback

Zend\Validator\Callback allows you to provide a callback with which to validate a given value.

Supported options for Zend\Validator\Callback

The following options are supported for Zend\Validator\Callback:

  • callback: Sets the callback which will be called for the validation.
  • options: Sets the additional options which will be given to the callback.

Basic usage

The simplest usecase is to have a single function and use it as a callback. Let’s expect we have the following function.

1
2
3
4
5
function myMethod($value)
{
    // some validation
    return true;
}

To use it within Zend\Validator\Callback you just have to call it this way:

1
2
3
4
5
6
$valid = new Zend\Validator\Callback('myMethod');
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Usage with closures

PHP 5.3 introduces closures, which are basically self-contained or anonymous functions. PHP considers closures another form of callback, and, as such, may be used with Zend\Validator\Callback. As an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$valid = new Zend\Validator\Callback(function($value){
    // some validation
    return true;
});

if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Usage with class-based callbacks

Of course it’s also possible to use a class method as callback. Let’s expect we have the following class method:

1
2
3
4
5
6
7
8
class MyClass
{
    public function myMethod($value)
    {
        // some validation
        return true;
    }
}

The definition of the callback is in this case almost the same. You have just to create an instance of the class before the method and create an array describing the callback:

1
2
3
4
5
6
7
$object = new MyClass;
$valid = new Zend\Validator\Callback(array($object, 'myMethod'));
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

You may also define a static method as a callback. Consider the following class definition and validator usage:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class MyClass
{
    public static function test($value)
    {
        // some validation
        return true;
    }
}

$valid = new Zend\Validator\Callback(array('MyClass', 'test'));
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Finally, if you are using PHP 5.3, you may define the magic method __invoke() in your class. If you do so, simply providing an instance of the class as the callback will also work:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class MyClass
{
    public function __invoke($value)
    {
        // some validation
        return true;
    }
}

$object = new MyClass();
$valid = new Zend\Validator\Callback($object);
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Adding options

Zend\Validator\Callback also allows the usage of options which are provided as additional arguments to the callback.

Consider the following class and method definition:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class MyClass
{
    function myMethod($value, $option)
    {
        // some validation
        return true;
    }

    //if a context is present
    function myMethod($value, $context, $option)
    {
        // some validation
        return true;
    }

}

There are two ways to inform the validator of additional options: pass them in the constructor, or pass them to the setOptions() method.

To pass them to the constructor, you would need to pass an array containing two keys, “callback” and “options”:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$valid = new Zend\Validator\Callback(array(
    'callback' => array('MyClass', 'myMethod'),
    'options'  => $option,
));

if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Otherwise, you may pass them to the validator after instantiation:

1
2
3
4
5
6
7
8
$valid = new Zend\Validator\Callback(array('MyClass', 'myMethod'));
$valid->setOptions($option);

if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

When there are additional values given to isValid() then these values will be added immediately after $value.

1
2
3
4
5
6
7
8
$valid = new Zend\Validator\Callback(array('MyClass', 'myMethod'));
$valid->setOptions($option);

if ($valid->isValid($input, $additional)) {
    // input appears to be valid
} else {
    // input is invalid
}

When making the call to the callback, the value to be validated will always be passed as the first argument to the callback followed by all other values given to isValid(); all other options will follow it. The amount and type of options which can be used is not limited.

CreditCard

Zend\Validator\CreditCard allows you to validate if a given value could be a credit card number.

A credit card contains several items of metadata, including a hologram, account number, logo, expiration date, security code and the card holder name. The algorithms for verifying the combination of metadata are only known to the issuing company, and should be verified with them for purposes of payment. However, it’s often useful to know whether or not a given number actually falls within the ranges of possible numbers prior to performing such verification, and, as such, Zend\Validator\CreditCard simply verifies that the credit card number provided is well-formed.

For those cases where you have a service that can perform comprehensive verification, Zend\Validator\CreditCard also provides the ability to attach a service callback to trigger once the credit card number has been deemed valid; this callback will then be triggered, and its return value will determine overall validity.

The following issuing institutes are accepted:

  • American Express
  • China UnionPay
  • Diners Club Card Blanche
  • Diners Club International
  • Diners Club US & Canada
  • Discover Card
  • JCB
  • Laser
  • Maestro
  • MasterCard
  • Solo
  • Visa
  • Visa Electron

Note

Invalid institutes

The institutes Bankcard and Diners Club enRoute do not exist anymore. Therefore they are treated as invalid.

Switch has been rebranded to Visa and is therefore also treated as invalid.

Supported options for Zend\Validator\CreditCard

The following options are supported for Zend\Validator\CreditCard:

  • service: A callback to an online service which will additionally be used for the validation.
  • type: The type of credit card which will be validated. See the below list of institutes for details.

Basic usage

There are several credit card institutes which can be validated by Zend\Validator\CreditCard. Per default, all known institutes will be accepted. See the following example:

1
2
3
4
5
6
$valid = new Zend\Validator\CreditCard();
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

The above example would validate against all known credit card institutes.

Accepting defined credit cards

Sometimes it is necessary to accept only defined credit card institutes instead of all; e.g., when you have a webshop which accepts only Visa and American Express cards.