Introduction

Standard Validation Classes

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

Alnum

Zend_Validate_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 Zend_Validate_Alnum

The following options are supported for Zend_Validate_Alnum:

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

Basic usage

A basic example is the following one:

  1. span style="color: #ff0000;">'Abcd12')) {
  2.     // value contains only allowed chars
  3. // false
  4. }

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. span style="color: #ff0000;">'allowWhiteSpace''Abcd and 12')) {
  2.     // value contains only allowed chars
  3. // false
  4. }

Using different languages

When using Zend_Validate_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 completly 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_Validate_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_Validate_Alnum validator with the exception that it does not accept digits.

Supported options for Zend_Validate_Alpha

The following options are supported for Zend_Validate_Alpha:

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

Basic usage

A basic example is the following one:

  1. span style="color: #ff0000;">'Abcd')) {
  2.     // value contains only allowed chars
  3. // false
  4. }

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. span style="color: #ff0000;">'allowWhiteSpace''Abcd and efg')) {
  2.     // value contains only allowed chars
  3. // false
  4. }

Using different languages

When using Zend_Validate_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 completly 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_Validate_Barcode allows you to check if a given value can be represented as barcode.

Zend_Validate_Barcode supports multiple barcode standards and can be extended with proprietary barcode implementations very easily. The following barcode standards are supported:

  • 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 usecases 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 superceded 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, uppercased 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 "Univeral Product Code".

    This barcode preceeded 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_Validate_Barcode

The following options are supported for Zend_Validate_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 classname.

  • 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. span style="color: #ff0000;">'EAN13'// input appears to be valid
  2. // input is invalid
  3. }

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. span style="color: #ff0000;">'adapter'  => 'EAN13',
  2.     'checksum'// input appears to be valid
  3. // input is invalid
  4. }

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_Validate_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_Validate_Barcode_AdapterAbstract or implement Zend_Validate_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. span style="color: #ff0000;">'even''0123456789ABCDE''_mod66'// do some validations and return a boolean
  2. 'My_Barcode_MyBar'// input appears to be valid
  3. // input is invalid
  4. }

Between

Zend_Validate_Between allows you to validate if a given value is between two other values.

Note: Zend_Validate_Between supports only number validation
It should be noted that Zend_Validate_Between supports only the validation of numbers. Strings or dates can not be validated with this validator.

Supported options for Zend_Validate_Between

The following options are supported for Zend_Validate_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_Validate_Between

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

  1. span style="color: #ff0000;">'min' => 0, 'max' => 10));
  2. $value  = 10;
  3. $result = $valid->isValid($value);
  4. // 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. span style="color: #ff0000;">'min' => 0,
  2.         'max' => 10,
  3.         'inclusive'// 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_Validate_Callback allows you to provide a callback with which to validate a given value.

Supported options for Zend_Validate_Callback

The following options are supported for Zend_Validate_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. span style="color: #808080; font-style: italic;">// some validation

To use it within Zend_Validate_Callback you just have to call it this way:

  1. span style="color: #ff0000;">'myMethod'// input appears to be valid
  2. // input is invalid
  3. }

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_Validate_Callback. As an example:

  1. span style="color: #808080; font-style: italic;">// some validation
  2. // input appears to be valid
  3. // input is invalid
  4. }

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. span style="color: #808080; font-style: italic;">// some validation

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. span style="color: #ff0000;">'myMethod'// input appears to be valid
  2. // input is invalid
  3. }

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

  1. span style="color: #808080; font-style: italic;">// some validation
  2. 'MyClass', 'test'// input appears to be valid
  3. // input is invalid
  4. }

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. span style="color: #808080; font-style: italic;">// some validation
  2. // input appears to be valid
  3. // input is invalid
  4. }

Adding options

Zend_Validate_Callback also allows the usage of options which are provided as additional arguments to the callback.

Consider the following class and method definition:

  1. span style="color: #808080; font-style: italic;">// some validation

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. span style="color: #ff0000;">'callback''MyClass', 'myMethod'),
  2.     'options'// input appears to be valid
  3. // input is invalid
  4. }

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

  1. span style="color: #ff0000;">'MyClass', 'myMethod'// input appears to be valid
  2. // input is invalid
  3. }

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

  1. span style="color: #ff0000;">'MyClass', 'myMethod'// input appears to be valid
  2. // input is invalid
  3. }

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_Validate_CreditCard allows you to validate if a given value could be a credit card number.

A creditcard 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_Validate_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_Validate_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_Validate_CreditCard

The following options are supported for Zend_Validate_CreditCard:

  • service: A callback to an online service which will additionally be used for the validation.

  • type: The type of creditcard 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_Validate_CreditCard. Per default, all known institutes will be accepted. See the folowing example:

  1. span style="color: #808080; font-style: italic;">// input appears to be valid
  2. // input is invalid
  3. }

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. Zend_Validate_CreditCard allows you to do exactly this by limiting it to exactly these institutes.

To use a limitation you can either provide specific institutes at initiation, or afterwards by using setType(). Each can take several arguments.

You can provide a single institute:

  1.  

When you want to allow multiple institutes, then you can provide them as array:

  1.  

And as with all validators, you can also pass an associative array of options or an instance of Zend_Config. In this case you have to provide the institutes with the type array key as simulated here:

  1. span style="color: #ff0000;">'type'
Constants for credit card institutes
Institute Constant
American Express AMERICAN_EXPRESS
China UnionPay UNIONPAY
Diners Club Card Blanche DINERS_CLUB
Diners Club International DINERS_CLUB
Diners Club US & Canada DINERS_CLUB_US
Discover Card DISCOVER
JCB JCB
Laser LASER
Maestro MAESTRO
MasterCard MASTERCARD
Solo SOLO
Visa VISA
Visa Electron VISA

You can also set or add institutes afterward instantiation by using the methods setType(), addType() and getType().

  1.  

Note: Default institute
When no institute is given at initiation then ALL will be used, which sets all institutes at once.
In this case the usage of addType() is useless because all institutes are already added.

Validation by using foreign APIs

As said before Zend_Validate_CreditCard will only validate the credit card number. Fortunately, some institutes provide online APIs which can validate a credit card number by using algorithms which are not available to the public. Most of these services are paid services. Therefore, this check is deactivated per default.

When you have access to such an API, then you can use it as an addon for Zend_Validate_CreditCard and increase the security of the validation.

To do so, you simply need to give a callback which will be called when the generic validation has passed. This prevents the API from being called for invalid numbers, which increases the performance of the application.

setService() sets a new service, and getService() returns the set service. As a configuration option, you can give the array key 'service' at initiation. For details about possible options take a look into Callback.

  1. // Your service class
  2. // some online validation
  3.     }
  4. }
  5.  
  6. // The validation
  7. 'checkOnline'));

As you can see the callback method will be called with the creditcard number as the first parameter, and the accepted types as the second parameter.

Ccnum

Note: The Ccnum validator has been deprecated in favor of the CreditCard validator. For security reasons you should use CreditCard instead of Ccnum.

Date

Zend_Validate_Date allows you to validate if a given value contains a date. This validator validates also localized input.

Supported options for Zend_Validate_Date

The following options are supported for Zend_Validate_Date:

  • format: Sets the format which is used to write the date.

  • locale: Sets the locale which will be used to validate date values.

Default date validation

The easiest way to validate a date is by using the default date format. It is used when no locale and no format has been given.

  1. span style="color: #ff0000;">'2000-10-10');   // returns true
  2. $validator->isValid('10.10.2000'); // returns false

The default date format for Zend_Validate_Date is 'yyyy-MM-dd'.

Localized date validation

Zend_Validate_Date validates also dates which are given in a localized format. By using the locale option you can define the locale which the date format should use for validation.

  1. span style="color: #ff0000;">'locale' => 'de'));
  2.  
  3. $validator->isValid('10.Feb.2010'); // returns true
  4. $validator->isValid('10.May.2010'); // returns false

The locale option sets the default date format. In the above example this is 'dd.MM.yyyy' which is defined as default date format for 'de'.

Self defined date validation

Zend_Validate_Date supports also self defined date formats. When you want to validate such a date you can use the format option.

  1. span style="color: #ff0000;">'format' => 'yyyy'));
  2.  
  3. $validator->isValid('2010'); // returns true
  4. $validator->isValid('May')// returns false

Of course you can combine format and locale. In this case you can also use localized month or daynames.

  1. span style="color: #ff0000;">'format' => 'yyyy MMMM', 'locale' => 'de'));
  2.  
  3. $validator->isValid('2010 Dezember'); // returns true
  4. $validator->isValid('2010 June');     // returns false

Db_RecordExists and Db_NoRecordExists

Zend_Validate_Db_RecordExists and Zend_Validate_Db_NoRecordExists provide a means to test whether a record exists in a given table of a database, with a given value.

Supported options for Zend_Validate_Db_*

The following options are supported for Zend_Validate_Db_NoRecordExists and Zend_Validate_Db_RecordExists:

  • adapter: The database adapter which will be used for the search.

  • exclude: Sets records which will be excluded from the search.

  • field: The database field within this table which will be searched for the record.

  • schema: Sets the schema which will be used for the search.

  • table: The table which will be searched for the record.

Basic usage

An example of basic usage of the validators:

  1. //Check that the email address exists in the database
  2. 'table' => 'users',
  3.         'field' => 'emailaddress'// email address appears to be valid
  4. // email address is invalid; print the reasons
  5. "$message\n";
  6.     }
  7. }

The above will test that a given email address is in the database table. If no record is found containing the value of $emailaddress in the specified column, then an error message is displayed.

  1. //Check that the username is not present in the database
  2. 'table' => 'users',
  3.         'field' => 'username'// username appears to be valid
  4. // username is invalid; print the reason
  5. "$message\n";
  6.     }
  7. }

The above will test that a given username is not in the database table. If a record is found containing the value of $username in the specified column, then an error message is displayed.

Excluding records

Zend_Validate_Db_RecordExists and Zend_Validate_Db_NoRecordExists also provide a means to test the database, excluding a part of the table, either by providing a where clause as a string, or an array with the keys "field" and "value".

When providing an array for the exclude clause, the != operator is used, so you can check the rest of a table for a value before altering a record (for example on a user profile form)

  1. //Check no other users have the username
  2. 'table' => 'users',
  3.         'field' => 'username',
  4.         'exclude''field' => 'id',
  5.             'value'// username appears to be valid
  6. // username is invalid; print the reason
  7. "$message\n";
  8.     }
  9. }

The above example will check the table to ensure no records other than the one where id = $user_id contains the value $username.

You can also provide a string to the exclude clause so you can use an operator other than !=. This can be useful for testing against composite keys.

  1. span style="color: #ff0000;">'[email protected]';
  2. $clause    = $db->quoteInto('email = ?''table'   => 'users',
  3.         'field'   => 'username',
  4.         'exclude'// username appears to be valid
  5. // username is invalid; print the reason
  6. "$message\n";
  7.     }
  8. }

The above example will check the 'users' table to ensure that only a record with both the username $username and with the email $email is valid.

Database Adapters

You can also specify an adapter. This will allow you to work with applications using multiple database adapters, or where you have not set a default adapter. As in the example below:

  1. span style="color: #ff0000;">'table' => 'users',
  2.         'field' => 'id',
  3.         'adapter' => $dbAdapter
  4.     )
  5. );

Database Schemas

You can specify a schema within your database for adapters such as PostgreSQL and DB/2 by simply supplying an array with table and schema keys. As in the example below:

  1. span style="color: #ff0000;">'table'  => 'users',
  2.         'schema' => 'my',
  3.         'field'  => 'id'
  4.     )
  5. );

Digits

Zend_Validate_Digits validates if a given value contains only digits.

Supported options for Zend_Validate_Digits

There are no additional options for Zend_Validate_Digits:

Validating digits

To validate if a given value contains only digits and no other characters, simply call the validator like shown in this example:

  1. span style="color: #ff0000;">"1234567890"); // returns true
  2. $validator->isValid(1234);         // returns true
  3. $validator->isValid('1a234');      // returns false

Note: Validating numbers
When you want to validate numbers or numeric values, be aware that this validator only validates digits. This means that any other sign like a thousand separator or a comma will not pass this validator. In this case you should use Zend_Validate_Int or Zend_Validate_Float.

EmailAddress

Zend_Validate_EmailAddress allows you to validate an email address. The validator first splits the email address on local-part @ hostname and attempts to match these against known specifications for email addresses and hostnames.

Basic usage

A basic example of usage is below:

  1. span style="color: #808080; font-style: italic;">// email appears to be valid
  2. // email is invalid; print the reasons
  3. "$message\n";
  4.     }
  5. }

This will match the email address $email and on failure populate getMessages() with useful error messages.

Options for validating Email Addresses

Zend_Validate_EmailAddress supports several options which can either be set at initiation, by giving an array with the related options, or afterwards, by using setOptions(). The following options are supported:

  • allow: Defines which type of domain names are accepted. This option is used in conjunction with the hostname option to set the hostname validator. For more informations about possible values of this option, look at Hostname and possible ALLOW* constants. This option defaults to ALLOW_DNS.

  • deep: Defines if the servers MX records should be verified by a deep check. When this option is set to TRUE then additionally to MX records also the A, A6 and AAAA records are used to verify if the server accepts emails. This option defaults to FALSE.

  • domain: Defines if the domain part should be checked. When this option is set to FALSE, then only the local part of the email address will be checked. In this case the hostname validator will not be called. This option defaults to TRUE.

  • hostname: Sets the hostname validator with which the domain part of the email address will be validated.

  • mx: Defines if the MX records from the server should be detected. If this option is defined to TRUE then the MX records are used to verify if the server accepts emails. This option defaults to FALSE.

  1. span style="color: #ff0000;">'domain'

Complex local parts

Zend_Validate_EmailAddress will match any valid email address according to RFC2822. For example, valid emails include [email protected], [email protected], "bob@jones"@domain.com and "bob jones"@domain.com.

Some obsolete email formats will not currently validate (e.g. carriage returns or a "\" character in an email address).

Validating only the local part

If you need Zend_Validate_EmailAddress to check only the local part of an email address, and want to disable validation of the hostname, you can set the domain option to FALSE. This forces Zend_Validate_EmailAddress not to validate the hostname part of the email address.

  1. span style="color: #ff0000;">'domain'

Validating different types of hostnames

The hostname part of an email address is validated against Zend_Validate_Hostname. By default only DNS hostnames of the form domain.com are accepted, though if you wish you can accept IP addresses and Local hostnames too.

To do this you need to instantiate Zend_Validate_EmailAddress passing a parameter to indicate the type of hostnames you want to accept. More details are included in Zend_Validate_Hostname, though an example of how to accept both DNS and Local hostnames appears below:

  1. span style="color: #808080; font-style: italic;">// email appears to be valid
  2. // email is invalid; print the reasons
  3. "$message\n";
  4.     }
  5. }

Checking if the hostname actually accepts email

Just because an email address is in the correct format, it doesn't necessarily mean that email address actually exists. To help solve this problem, you can use MX validation to check whether an MX (email) entry exists in the DNS record for the email's hostname. This tells you that the hostname accepts email, but doesn't tell you the exact email address itself is valid.

MX checking is not enabled by default. To enable MX checking you can pass a second parameter to the Zend_Validate_EmailAddress constructor.

  1. span style="color: #ff0000;">'allow''mx'

Note: MX Check under Windows
Within Windows environments MX checking is only available when PHP 5.3 or above is used. Below PHP 5.3 MX checking will not be used even if it's activated within the options.

Alternatively you can either pass TRUE or FALSE to setValidateMx() to enable or disable MX validation.

By enabling this setting network functions will be used to check for the presence of an MX record on the hostname of the email address you wish to validate. Please be aware this will likely slow your script down.

Sometimes validation for MX records returns FALSE, even if emails are accepted. The reason behind this behaviour is, that servers can accept emails even if they do not provide a MX record. In this case they can provide A, A6 or AAAA records. To allow Zend_Validate_EmailAddress to check also for these other records, you need to set deep MX validation. This can be done at initiation by setting the deep option or by using setOptions().

  1. span style="color: #ff0000;">'allow''mx''deep'
Warning

Performance warning

You should be aware that enabling MX check will slow down you script because of the used network functions. Enabling deep check will slow down your script even more as it searches the given server for 3 additional types.

Note: Disallowed IP addresses
You should note that MX validation is only accepted for external servers. When deep MX validation is enabled, then local IP addresses like 192.168.* or 169.254.* are not accepted.

Validating International Domains Names

Zend_Validate_EmailAddress will also match international characters that exist in some domains. This is known as International Domain Name (IDN) support. This is enabled by default, though you can disable this by changing the setting via the internal Zend_Validate_Hostname object that exists within Zend_Validate_EmailAddress.

  1.  

More information on the usage of setValidateIdn() appears in the Zend_Validate_Hostname documentation.

Please note IDNs are only validated if you allow DNS hostnames to be validated.

Validating Top Level Domains

By default a hostname will be checked against a list of known TLDs. This is enabled by default, though you can disable this by changing the setting via the internal Zend_Validate_Hostname object that exists within Zend_Validate_EmailAddress.

  1.  

More information on the usage of setValidateTld() appears in the Zend_Validate_Hostname documentation.

Please note TLDs are only validated if you allow DNS hostnames to be validated.

Setting messages

Zend_Validate_EmailAddress makes also use of Zend_Validate_Hostname to check the hostname part of a given email address. As with Zend Framework 1.10 you can simply set messages for Zend_Validate_Hostname from within Zend_Validate_EmailAddress.

  1. span style="color: #ff0000;">"I don't know the TLD you gave"
  2.     )
  3. );

Before Zend Framework 1.10 you had to attach the messages to your own Zend_Validate_Hostname, and then set this validator within Zend_Validate_EmailAddress to get your own messages returned.

Float

Zend_Validate_Float allows you to validate if a given value contains a floating-point value. This validator validates also localized input.

Supported options for Zend_Validate_Float

The following options are supported for Zend_Validate_Float:

  • locale: Sets the locale which will be used to validate localized float values.

Simple float validation

The simplest way to validate a float is by using the system settings. When no option is used, the environment locale is used for validation:

  1. span style="color: #808080; font-style: italic;">// returns true
  2. $validator->isValid('10a01'); // returns false
  3. $validator->isValid('1,234.5'); // returns true

In the above example we expected that our environment is set to "en" as locale.

Localized float validation

Often it's useful to be able to validate also localized values. Float values are often written different in other countries. For example using english you will write "1.5". In german you may write "1,5" and in other languages you may use grouping.

Zend_Validate_Float is able to validate such notations. But it is limited to the locale you set. See the following code:

  1. span style="color: #ff0000;">'locale' => 'de'));
  2.  
  3. $validator->isValid(1234.5); // returns true
  4. $validator->isValid("1 234,5"); // returns false
  5. $validator->isValid("1.234"); // returns true

As you can see, by using a locale, your input is validated localized. Using a different notation you get a FALSE when the locale forces a different notation.

The locale can also be set afterwards by using setLocale() and retrieved by using getLocale().

GreaterThan

Zend_Validate_GreaterThan allows you to validate if a given value is greater than a minimum border value.

Note: Zend_Validate_GreaterThan supports only number validation
It should be noted that Zend_Validate_GreaterThan supports only the validation of numbers. Strings or dates can not be validated with this validator.

Supported options for Zend_Validate_GreaterThan

The following options are supported for Zend_Validate_GreaterThan:

  • min: Sets the minimum border value.

Basic usage

To validate if a given value is greater than a defined border simply use the following example.

  1. span style="color: #ff0000;">'min'// returns true

The above example returns TRUE for all values which are greater than 10.

  1. span style="color: #ff0000;">'min'// returns false

The above example returns FALSE for all values which are lesser or equal to the minimum border value.

Hex

Zend_Validate_Hex allows you to validate if a given value contains only hexadecimal characters. These are all characters from 0 to 9 and A to F case insensitive. There is no length limitation for the input you want to validate.

  1. span style="color: #ff0000;">'123ABC')) {
  2.     // value contains only hex chars
  3. // false
  4. }

Note: Invalid characters
All other characters will return false, including whitespace and decimal point. Also unicode zeros and numbers from other scripts than latin will not be treaten as valid.

Supported options for Zend_Validate_Hex

There are no additional options for Zend_Validate_Hex:

Hostname

Zend_Validate_Hostname allows you to validate a hostname against a set of known specifications. It is possible to check for three different types of hostnames: a DNS Hostname (i.e. domain.com), IP address (i.e. 1.2.3.4), and Local hostnames (i.e. localhost). By default only DNS hostnames are matched.

Supported options for Zend_Validate_Hostname

The following options are supported for Zend_Validate_Hostname:

  • allow: Defines the sort of hostname which is allowed to be used. See Hostname types for details.

  • idn: Defines if IDN domains are allowed or not. This option defaults to TRUE.

  • ip: Allows to define a own IP validator. This option defaults to a new instance of Zend_Validate_Ip.

  • tld: Defines if TLDs are validated. This option defaults to TRUE.

Basic usage

A basic example of usage is below:

  1. span style="color: #808080; font-style: italic;">// hostname appears to be valid
  2. // hostname is invalid; print the reasons
  3. "$message\n";
  4.     }
  5. }

This will match the hostname $hostname and on failure populate getMessages() with useful error messages.

Validating different types of hostnames

You may find you also want to match IP addresses, Local hostnames, or a combination of all allowed types. This can be done by passing a parameter to Zend_Validate_Hostname when you instantiate it. The parameter should be an integer which determines what types of hostnames are allowed. You are encouraged to use the Zend_Validate_Hostname constants to do this.

The Zend_Validate_Hostname constants are: ALLOW_DNS to allow only DNS hostnames, ALLOW_IP to allow IP addresses, ALLOW_LOCAL to allow local network names, ALLOW_URI to allow » RFC3986-compliant addresses, and ALLOW_ALL to allow all four above types.

Note: Additional Information on ALLOW_URI
ALLOW_URI allows to check hostnames according to » RFC3986. These are registered names which are used by WINS, NetInfo and also local hostnames like those defined within your .hosts file.

To just check for IP addresses you can use the example below:

  1. span style="color: #808080; font-style: italic;">// hostname appears to be valid
  2. // hostname is invalid; print the reasons
  3. "$message\n";
  4.     }
  5. }

As well as using ALLOW_ALL to accept all common hostnames types you can combine these types to allow for combinations. For example, to accept DNS and Local hostnames instantiate your Zend_Validate_Hostname object as so:

  1.  

Validating International Domains Names

Some Country Code Top Level Domains (ccTLDs), such as 'de' (Germany), support international characters in domain names. These are known as International Domain Names (IDN). These domains can be matched by Zend_Validate_Hostname via extended characters that are used in the validation process.

Note: IDN domains
Until now more than 50 ccTLDs support IDN domains.

To match an IDN domain it's as simple as just using the standard Hostname validator since IDN matching is enabled by default. If you wish to disable IDN validation this can be done by either passing a parameter to the Zend_Validate_Hostname constructor or via the setValidateIdn() method.

You can disable IDN validation by passing a second parameter to the Zend_Validate_Hostname constructor in the following way.

  1. span style="color: #ff0000;">'allow''idn'

Alternatively you can either pass TRUE or FALSE to setValidateIdn() to enable or disable IDN validation. If you are trying to match an IDN hostname which isn't currently supported it is likely it will fail validation if it has any international characters in it. Where a ccTLD file doesn't exist in Zend/Validate/Hostname specifying the additional characters a normal hostname validation is performed.

Note: IDN validation
Please note that IDNs are only validated if you allow DNS hostnames to be validated.

Validating Top Level Domains

By default a hostname will be checked against a list of known TLDs. If this functionality is not required it can be disabled in much the same way as disabling IDN support. You can disable TLD validation by passing a third parameter to the Zend_Validate_Hostname constructor. In the example below we are supporting IDN validation via the second parameter.

  1. span style="color: #ff0000;">'allow''idn''tld'

Alternatively you can either pass TRUE or FALSE to setValidateTld() to enable or disable TLD validation.

Note: TLD validation
Please note TLDs are only validated if you allow DNS hostnames to be validated.

Iban

Zend_Validate_Iban validates if a given value could be a IBAN number. IBAN is the abbreviation for "International Bank Account Number".

Supported options for Zend_Validate_Iban

The following options are supported for Zend_Validate_Iban:

  • locale: Sets the locale which is used to get the IBAN format for validation.

IBAN validation

IBAN numbers are always related to a country. This means that different countries use different formats for their IBAN numbers. This is the reason why IBAN numbers always need a locale. By knowing this we already know how to use Zend_Validate_Iban.

Application wide locale

We could use the application wide locale. This means that when no option is given at initiation, Zend_Validate_Iban searches for the application wide locale. See the following code snippet:

  1. // within bootstrap
  2. 'Zend_Locale''de_AT'));
  3.  
  4. // within the module
  5. 'AT611904300234573201')) {
  6.     // IBAN appears to be valid
  7. // IBAN is not valid
  8. }

Note: Application wide locale
Of course this works only when an application wide locale was set within the registry previously. Otherwise Zend_Locale will try to use the locale which the client sends or, when non has been send, it uses the environment locale. Be aware that this can lead to unwanted behaviour within the validation.

Ungreedy IBAN validation

Sometime it is usefull, just to validate if the given value is a IBAN number or not. This means that you don't want to validate it against a defined country. This can be done by using a FALSE as locale.

  1. span style="color: #ff0000;">'locale'// Note: you can also set a FALSE as single parameter
  2. 'AT611904300234573201')) {
  3.     // IBAN appears to be valid
  4. // IBAN is not valid
  5. }

So any IBAN number will be valid. Note that this should not be done when you accept only accounts from a single country.

Region aware IBAN validation

To validate against a defined country, you just need to give the wished locale. You can do this by the option locale and also afterwards by using setLocale().

  1. span style="color: #ff0000;">'locale' => 'de_AT''AT611904300234573201')) {
  2.     // IBAN appears to be valid
  3. // IBAN is not valid
  4. }

Note: Use full qualified locales
You must give a full qualified locale, otherwise the country could not be detected correct because languages are spoken in multiple countries.

Identical

Zend_Validate_Identical allows you to validate if a given value is identical with an set haystack.

Supported options for Zend_Validate_Identical

The following options are supported for Zend_Validate_Identical:

  • strict: Defines if the validation should be done strict. The default value is TRUE.

  • token: Sets the token with which the input will be validated against.

Basic usage

To validate if two values are identical you need to set the origin value as haystack. See the following example which validates two strings.

  1. span style="color: #ff0000;">'origin'

The validation will only then return TRUE when both values are 100% identical. In our example, when $value is 'origin'.

You can set the wished token also afterwards by using the method setToken() and getToken() to get the actual set token.

Identical objects

Of course Zend_Validate_Identical can not only validate strings, but also any other variable type like Boolean, Integer, Float, Array or even Objects. As already noted Haystack and Value must be identical.

  1. span style="color: #808080; font-style: italic;">// input appears to be valid
  2. // input is invalid
  3. }

Note: Type comparison
You should be aware that also the type of a variable is used for validation. This means that the string '3' is not identical with the integer 3. When you want such a non strict validation you must set the strict option.

Form elements

Zend_Validate_Identical supports also the comparison of form elements. This can be done by using the element's name as token. See the following example:

  1. span style="color: #ff0000;">'password', 'elementOne''password', 'elementTwo''validators''identical''token' => 'elementOne'))
  2.     )
  3. ));

By using the elements name from the first element as token for the second element, the validator validates if the second element is equal with the first element. In the case your user does not enter two identical values, you will get an validation error.

Strict validation

As mentioned before Zend_Validate_Identical validates tokens strict. You can change this behaviour by using the strict option. The default value for this property is TRUE.

  1. span style="color: #ff0000;">'token' => 123, 'strict''123'// input appears to be valid
  2. // input is invalid
  3. }

The difference to the previous example is that the validation returns in this case TRUE, even if you compare a integer with string value as long as the content is identical but not the type.

For convinience you can also use setStrict() and getStrict().

Configuration

As all other validators also Zend_Validate_Identical supports the usage of configuration settings as input parameter. This means that you can configure this validator with an Zend_Config object.

But this adds one case which you have to be aware. When you are using an array as haystack then you should wrap it within an 'token' key when it could contain only one element.

  1. span style="color: #ff0000;">'token'// input appears to be valid
  2. // input is invalid
  3. }

The above example validates the integer 123. The reason for this special case is, that you can configure the token which has to be used by giving the 'token' key.

So, when your haystack contains one element and this element is named 'token' then you have to wrap it like shown in the example below.

  1. span style="color: #ff0000;">'token''token'// input appears to be valid
  2. // input is invalid
  3. }

InArray

Zend_Validate_InArray allows you to validate if a given value is contained within an array. It is also able to validate multidimensional arrays.

Supported options for Zend_Validate_InArray

The following options are supported for Zend_Validate_InArray:

  • haystack: Sets the haystack for the validation.

  • recursive: Defines if the validation should be done recursive. This option defaults to FALSE.

  • strict: Defines if the validation should be done strict. This option defaults to FALSE.

Simple array validation

The simplest way, is just to give the array which should be searched against at initiation:

  1. span style="color: #ff0000;">'key' => 'value',
  2.                                              'otherkey' => 'othervalue''value')) {
  3.     // value found
  4. // no value found
  5. }

This will behave exactly like PHP's in_array() method.

Note: Per default this validation is not strict nor can it validate multidimensional arrays.

Of course you can give the array to validate against also afterwards by using the setHaystack() method. getHaystack() returns the actual set haystack array.

  1. span style="color: #ff0000;">'key' => 'value', 'otherkey' => 'othervalue''value')) {
  2.     // value found
  3. // no value found
  4. }

Strict array validation

As mentioned before you can also do a strict validation within the array. Per default there would be no difference between the integer value 0 and the string "0". When doing a strict validation this difference will also be validated and only same types are accepted.

A strict validation can also be done by using two different ways. At initiation and by using a method. At initiation you have to give an array with the following structure:

  1. span style="color: #ff0000;">'haystack''key' => 'value', 'otherkey' => 'othervalue'),
  2.         'strict''value')) {
  3.     // value found
  4. // no value found
  5. }

The haystack key contains your array to validate against. And by setting the strict key to TRUE, the validation is done by using a strict type check.

Of course you can also use the setStrict() method to change this setting afterwards and getStrict() to get the actual set state.

Note: Note that the strict setting is per default FALSE.

Recursive array validation

In addition to PHP's in_array() method this validator can also be used to validate multidimensional arrays.

To validate multidimensional arrays you have to set the recursive option.

  1. span style="color: #ff0000;">'haystack''firstDimension''key' => 'value',
  2.                                       'otherkey' => 'othervalue'),
  3.             'secondDimension''some' => 'real',
  4.                                        'different' => 'key')),
  5.         'recursive''value')) {
  6.     // value found
  7. // no value found
  8. }

Your array will then be validated recursive to see if the given value is contained. Additionally you could use setRecursive() to set this option afterwards and getRecursive() to retrieve it.

  1. span style="color: #ff0000;">'firstDimension''key' => 'value',
  2.                                   'otherkey' => 'othervalue'),
  3.         'secondDimension''some' => 'real',
  4.                                    'different' => 'key''value')) {
  5.     // value found
  6. // no value found
  7. }

Note: Default setting for recursion
Per default the recursive validation is turned off.

Note: Option keys within the haystack
When you are using the keys 'haystack', 'strict' or 'recursive' within your haystack, then you must wrap the haystack key.

Int

Zend_Validate_Int validates if a given value is an integer. Also localized integer values are recognised and can be validated.

Supported options for Zend_Validate_Int

The following options are supported for Zend_Validate_Int:

  • locale: Sets the locale which will be used to validate localized integers.

Simple integer validation

The simplest way to validate an integer is by using the system settings. When no option is used, the environment locale is used for validation:

  1. span style="color: #808080; font-style: italic;">// returns true
  2. $validator->isValid(1234.5); // returns false
  3. $validator->isValid('1,234'); // returns true

In the above example we expected that our environment is set to "en" as locale. As you can see in the third example also grouping is recognised.

Localized integer validation

Often it's useful to be able to validate also localized values. Integer values are often written different in other countries. For example using english you can write "1234" or "1,234". Both are integer values but the grouping is optional. In german for example you may write "1.234" and in french "1 234".

Zend_Validate_Int is able to validate such notations. But it is limited to the locale you set. This means that it not simply strips off the separator, it validates if the correct separator is used. See the following code:

  1. span style="color: #ff0000;">'locale' => 'de'));
  2.  
  3. $validator->isValid(1234); // returns true
  4. $validator->isValid("1,234"); // returns false
  5. $validator->isValid("1.234"); // returns true

As you can see, by using a locale, your input is validated localized. Using the english notation you get a FALSE when the locale forces a different notation.

The locale can also be set afterwards by using setLocale() and retrieved by using getLocale().

Ip

Zend_Validate_Ip allows you to validate if a given value is an IP address. It supports the IPv4 and also the IPv6 standard.

Supported options for Zend_Validate_Ip

The following options are supported for Zend_Validate_Ip:

  • allowipv4: Defines if the validator allows IPv4 adresses. This option defaults to TRUE.

  • allowipv6: Defines if the validator allows IPv6 adresses. This option defaults to TRUE.

Basic usage

A basic example of usage is below:

  1. span style="color: #808080; font-style: italic;">// ip appears to be valid
  2. // ip is invalid; print the reasons
  3. }

Note: Invalid IP addresses
Keep in mind that Zend_Validate_Ip only validates IP addresses. Addresses like 'mydomain.com' or '192.168.50.1/index.html' are no valid IP addresses. They are either hostnames or valid URLs but not IP addresses.

Note: IPv6 validation
Zend_Validate_Ip validates IPv6 addresses with regex. The reason is that the filters and methods from PHP itself don't follow the RFC. Many other available classes also don't follow it.

Validate IPv4 or IPV6 alone

Sometimes it's useful to validate only one of the supported formats. For example when your network only supports IPv4. In this case it would be useless to allow IPv6 within this validator.

To limit Zend_Validate_Ip to one protocol you can set the options allowipv4 or allowipv6 to FALSE. You can do this either by giving the option to the constructor or by using setOptions() afterwards.

  1. span style="color: #ff0000;">'allowipv6'// ip appears to be valid ipv4 address
  2. // ip is no ipv4 address
  3. }

Note: Default behaviour
The default behaviour which Zend_Validate_Ip follows is to allow both standards.

Isbn

Zend_Validate_Isbn allows you to validate an ISBN-10 or ISBN-13 value.

Supported options for Zend_Validate_Isbn

The following options are supported for Zend_Validate_Isbn:

  • separator: Defines the allowed separator for the ISBN number. It defaults to an empty string.

  • type: Defines the allowed type of ISBN numbers. It defaults to Zend_Validate_Isbn::AUTO. For details take a look at this section.

Basic usage

A basic example of usage is below:

  1. span style="color: #808080; font-style: italic;">// isbn is valid
  2. // isbn is not valid
  3. }

This will validate any ISBN-10 and ISBN-13 without separator.

Setting an explicit ISBN validation type

An example of an ISBN type restriction is below:

  1. span style="color: #808080; font-style: italic;">// OR
  2. 'type'// this is a valid ISBN-13 value
  3. // this is an invalid ISBN-13 value
  4. }

The above will validate only ISBN-13 values.

Valid types include:

  • Zend_Validate_Isbn::AUTO (default)

  • Zend_Validate_Isbn::ISBN10

  • Zend_Validate_Isbn::ISBN13

Specifying a separator restriction

An example of separator restriction is below:

  1. span style="color: #ff0000;">'-');
  2. // OR
  3. 'separator' => '-'// this is a valid ISBN with separator
  4. // this is an invalid ISBN with separator
  5. }

Note: Values without separator
This will return FALSE if $isbn doesn't contain a separator or if it's an invalid ISBN value.

Valid separators include:

  • "" (empty) (default)

  • "-" (hyphen)

  • " " (space)

LessThan

Zend_Validate_LessThan allows you to validate if a given value is less than a maximum border value. It is the cousine of Zend_Validate_GreaterThan.

Note: Zend_Validate_LessThan supports only number validation
It should be noted that Zend_Validate_LessThan supports only the validation of numbers. Strings or dates can not be validated with this validator.

Supported options for Zend_Validate_LessThan

The following options are supported for Zend_Validate_LessThan:

  • max: Sets the maximum allowed value.

Basic usage

To validate if a given value is less than a defined border simply use the following example.

  1. span style="color: #ff0000;">'max'// returns true

The above example returns TRUE for all values which are equal to 10 or lower than 10.

NotEmpty

This validator allows you to validate if a given 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.

Supported options for Zend_Validate_NotEmpty

The following options are supported for Zend_Validate_NotEmpty:

  • type: Sets the type of validation which will be processed. For details take a look into this section.

Default behaviour for Zend_Validate_NotEmpty

By default, this validator works differently than you would expect when you've worked with PHP's empty() function. In particular, this validator will evaluate both the integer 0 and string '0' as empty.

  1. span style="color: #ff0000;">'';
  2. $result = $valid->isValid($value);
  3. // returns false

Note: Default behaviour differs from PHP
Without providing configuration, Zend_Validate_NotEmpty's behaviour differs from PHP.

Changing behaviour for Zend_Validate_NotEmpty

Some projects have differing opinions of what is considered an "empty" value: a string with only whitespace might be considered empty, or 0 may be considered non-empty (particularly for boolean sequences). To accomodate differing needs, Zend_Validate_NotEmpty allows you to configure which types should be validated as empty and which not.

The following types can be handled:

  • boolean: Returns FALSE when the boolean value is FALSE.

  • integer: Returns FALSE when an integer 0 value is given. Per default this validation is not activated and returns TRUE on any integer values.

  • float: Returns FALSE when an float 0.0 value is given. Per default this validation is not activated and returns TRUE on any float values.

  • string: Returns FALSE when an empty string '' is given.

  • zero: Returns FALSE when the single character zero ('0') is given.

  • empty_array: Returns FALSE when an empty array is given.

  • null: Returns FALSE when an NULL value is given.

  • php: Returns FALSE on the same reasons where PHP method empty() would return TRUE.

  • space: Returns FALSE when an string is given which contains only whitespaces.

  • object: Returns TRUE. FALSE will be returned when object is not allowed but an object is given.

  • object_string: Returns FALSE when an object is given and it's __toString() method returns an empty string.

  • object_count: Returns FALSE when an object is given, it has an Countable interface and it's count is 0.

  • all: Returns FALSE on all above types.

All other given values will return TRUE per default.

There are several ways to select which of the above types are validated. You can give one or multiple types and add them, you can give an array, you can use constants, or you can give a textual string. See the following examples:

  1. // Returns false on 0
  2. // Returns false on 0 or '0'
  3. // Returns false on 0 or '0'
  4. // Returns false on 0 or '0'
  5. 'integer',
  6.     'zero',
  7. ));

You can also provide an instance of Zend_Config to set the desired types. To set types after instantiation, use the setType() method.

PostCode

Zend_Validate_PostCode allows you to determine if a given value is a valid postal code. Postal codes are specific to cities, and in some locales termed ZIP codes.

Zend_Validate_PostCode knows more than 160 different postal code formates. To select the correct format there are 2 ways. You can either use a fully qualified locale or you can set your own format manually.

Using a locale is more convenient as Zend Framework already knows the appropriate postal code format for each locale; however, you need to use the fully qualified locale (one containing a region specifier) to do so. For instance, the locale "de" is a locale but could not be used with Zend_Validate_PostCode as it does not include the region; "de_AT", however, would be a valid locale, as it specifies the region code ("AT", for Austria).

  1. span style="color: #ff0000;">'de_AT');

When you don't set a locale yourself, then Zend_Validate_PostCode will use the application wide set locale, or, when there is none, the locale returned by Zend_Locale.

  1. // application wide locale within your bootstrap
  2. 'de_AT''Zend_Locale'

You can also change the locale afterwards by calling setLocale(). And of course you can get the actual used locale by calling getLocale().

  1. span style="color: #ff0000;">'de_AT''en_GB');

Postal code formats themself are simply regular expression strings. When the international postal code format, which is used by setting the locale, does not fit your needs, then you can also manually set a format by calling setFormat().

  1. span style="color: #ff0000;">'de_AT''AT-\d{5}');

Note: Conventions for self defined formats
When using self defined formats you should omit the starting ('/^') and ending tags ('$/'). They are attached automatically.
You should also be aware that postcode values are always be validated in a strict way. This means that they have to be written standalone without additional characters when they are not covered by the format.

Constructor options

At it's most basic, you may pass either a Zend_Locale object or a string representing a fully qualified locale to the constructor of Zend_Validate_PostCode.

  1. span style="color: #ff0000;">'de_AT'

Additionally, you may pass either an array or a Zend_Config object to the constructor. When you do so, you must include either the key "locale" or "format"; these will be used to set the appropriate values in the validator object.

  1. span style="color: #ff0000;">'locale' => 'de_AT',
  2.     'format' => 'AT_\d+'
  3. ));

Supported options for Zend_Validate_PostCode

The following options are supported for Zend_Validate_PostCode:

  • format: Sets a postcode format which will be used for validation of the input.

  • locale: Sets a locale from which the postcode will be taken from.

Regex

This validator allows you to validate if a given string conforms a defined regular expression.

Supported options for Zend_Validate_Regex

The following options are supported for Zend_Validate_Regex:

  • pattern: Sets the regular expression pattern for this validator.

Validation with Zend_Validate_Regex

Validation with regular expressions allows to have complicated validations being done without writing a own validator. The usage of regular expression is quite common and simple. Let's look at some examples:

  1. span style="color: #ff0000;">'pattern' => '/^Test/');
  2.  
  3. $validator->isValid("Test"); // returns true
  4. $validator->isValid("Testing"); // returns true
  5. $validator->isValid("Pest"); // returns false

As you can see, the pattern has to be given using the same syntax as for preg_match(). For details about regular expressions take a look into » PHP's manual about PCRE pattern syntax.

Pattern handling

It is also possible to set a different pattern afterwards by using setPattern() and to get the actual set pattern with getPattern().

  1. span style="color: #ff0000;">'pattern' => '/^Test/');
  2. $validator->setPattern('ing$/');
  3.  
  4. $validator->isValid("Test"); // returns false
  5. $validator->isValid("Testing"); // returns true
  6. $validator->isValid("Pest"); // returns false

Sitemap Validators

The following validators conform to the » Sitemap XML protocol.

Sitemap_Changefreq

Validates whether a string is valid for using as a 'changefreq' element in a Sitemap XML document. Valid values are: 'always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', or 'never'.

Returns TRUE if and only if the value is a string and is equal to one of the frequencies specified above.

Sitemap_Lastmod

Validates whether a string is valid for using as a 'lastmod' element in a Sitemap XML document. The lastmod element should contain a W3C date string, optionally discarding information about time.

Returns TRUE if and only if the given value is a string and is valid according to the protocol.

Example #1 Sitemap Lastmod Validator

  1. span style="color: #ff0000;">'1999-11-11T22:23:52-02:00'); // true
  2. $validator->isValid('2008-05-12T00:42:52+02:00'); // true
  3. $validator->isValid('1999-11-11'); // true
  4. $validator->isValid('2008-05-12'); // true
  5.  
  6. $validator->isValid('1999-11-11t22:23:52-02:00'); // false
  7. $validator->isValid('2008-05-12T00:42:60+02:00'); // false
  8. $validator->isValid('1999-13-11'); // false
  9. $validator->isValid('2008-05-32'); // false
  10. $validator->isValid('yesterday'); // false

Sitemap_Loc

Validates whether a string is valid for using as a 'loc' element in a Sitemap XML document. This uses Zend_Form::check() internally. Read more at URI Validation.

Sitemap_Priority

Validates whether a value is valid for using as a 'priority' element in a Sitemap XML document. The value should be a decimal between 0.0 and 1.0. This validator accepts both numeric values and string values.

Example #2 Sitemap Priority Validator

  1. span style="color: #ff0000;">'0.1'); // true
  2. $validator->isValid('0.789'); // true
  3. $validator->isValid(0.8); // true
  4. $validator->isValid(1.0); // true
  5.  
  6. $validator->isValid('1.1'); // false
  7. $validator->isValid('-0.4'); // false
  8. $validator->isValid(1.00001); // false
  9. $validator->isValid(0xFF); // false
  10. $validator->isValid('foo'); // false

Supported options for Zend_Validate_Sitemap_*

There are no supported options for any of the Sitemap validators.

StringLength

This validator allows you to validate if a given string is between a defined length.

Note: Zend_Validate_StringLength supports only string validation
It should be noted that Zend_Validate_StringLength supports only the validation of strings. Integers, floats, dates or objects can not be validated with this validator.

Supported options for Zend_Validate_StringLength

The following options are supported for Zend_Validate_StringLength:

  • encoding: Sets the ICONV encoding which has to be used for this string.

  • min: Sets the minimum allowed length for a string.

  • max: Sets the maximum allowed length for a string.

Default behaviour for Zend_Validate_StringLength

Per default this validator checks if a value is between min and max. But for min the default value is 0 and for max it is NULL which means unlimited.

So per default, without giving any options, this validator only checks if the input is a string.

Limiting the maximum allowed length of a string

To limit the maximum allowed length of a string you need to set the max property. It accepts an integer value as input.

  1. span style="color: #ff0000;">'max' => 6));
  2.  
  3. $validator->isValid("Test"); // returns true
  4. $validator->isValid("Testing"); // returns false

You can set the maximum allowed length also afterwards by using the setMax() method. And getMax() to retrieve the actual maximum border.

  1. span style="color: #ff0000;">"Test"); // returns true
  2. $validator->isValid("Testing"); // returns false

Limiting the minimal required length of a string

To limit the minimal required length of a string you need to set the min property. It accepts also an integer value as input.

  1. span style="color: #ff0000;">'min' => 5));
  2.  
  3. $validator->isValid("Test"); // returns false
  4. $validator->isValid("Testing"); // returns true

You can set the minimal requested length also afterwards by using the setMin() method. And getMin() to retrieve the actual minimum border.

  1. span style="color: #ff0000;">"Test"); // returns false
  2. $validator->isValid("Testing"); // returns true

Limiting a string on both sides

Sometimes it is required to get a string which has a maximal defined length but which is also minimal chars long. For example when you have a textbox where a user can enter his name, then you may want to limit the name to maximum 30 chars but want to get sure that he entered his name. So you limit the mimimum required length to 3 chars. See the following example:

  1. span style="color: #ff0000;">'min' => 3, 'max' => 30));
  2.  
  3. $validator->isValid("."); // returns false
  4. $validator->isValid("Test"); // returns true
  5. $validator->isValid("Testing"); // returns true

Note: Setting a lower maximum border than the minimum border
When you try to set a lower maximum value as the actual minimum value, or a higher minimum value as the actual maximum value, then an exception will be raised.

Encoding of values

Strings are always using a encoding. Even when you don't set the encoding explicit, PHP uses one. When your application is using a different encoding than PHP itself then you should set an encoding yourself.

You can set your own encoding at initiation with the encoding option, or by using the setEncoding() method. We assume that your installation uses ISO and your application it set to ISO. In this case you will see the below behaviour.

  1. span style="color: #ff0000;">'min' => 6)
  2. );
  3. $validator->isValid("Ärger"); // returns false
  4.  
  5. $validator->setEncoding("UTF-8");
  6. $validator->isValid("Ärger"); // returns true
  7. 'min' => 6, 'encoding' => 'UTF-8')
  8. );
  9. $validator2->isValid("Ärger"); // returns true

So when your installation and your application are using different encodings, then you should always set an encoding yourself.


Introduction