Standard Validation ClassesZend Framework comes with a standard set of validation classes, which are ready for you to use. AlnumReturns TRUE if and only if $value contains only alphabetic and digit characters. This validator includes an option to also consider white space characters as valid.
AlphaReturns TRUE if and only if $value contains only alphabetic characters. This validator includes an option to also consider white space characters as valid. BarcodeZend_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:
Basic usageTo validate if a given string is a barcode you just need to know its type. See the following example for an EAN13 barcode:
Optional checksumSome 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.
Writing custom adaptersYou 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.
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.
BetweenReturns TRUE if and only if $value is between the minimum and maximum boundary values. The comparison is inclusive by default ($value may equal a boundary value), though this may be overridden in order to do a strict comparison, where $value must be strictly greater than the minimum and strictly less than the maximum. CallbackZend_Validate_Callback allows you to provide a callback with which to validate a given value. Basic usageThe simplest usecase is to have a single function and use it as a callback. Let's expect we have the following function.
To use it within Zend_Validate_Callback you just have to call it this way:
Usage with closuresPHP 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:
Usage with class-based callbacksOf course it's also possible to use a class method as callback. Let's expect we have the following class method:
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:
You may also define a static method as a callback. Consider the following class definition and validator usage: 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:
Adding optionsZend_Validate_Callback also allows the usage of options which are provided as additional arguments to the callback. Consider the following class and method definition:
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": Otherwise, you may pass them to the validator after instantiation:
When there are additional values given to isValid() then these values will be added immediately after $value.
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. CreditCardZend_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:
Basic usageThere 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:
The above example would validate against all known credit card institutes. Accepting defined credit cardsSometimes 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:
When you want to allow multiple institutes, then you can provide them as array:
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:
You can also set or add institutes afterward instantiation by using the methods setType(), addType() and getType().
Validation by using foreign APIsAs 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.
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. CcnumReturns TRUE if and only if $value follows the Luhn algorithm (mod-10 checksum) for credit card numbers.
DateReturns TRUE if $value is a valid date of the format 'YYYY-MM-DD'. If the optional locale option is set then the date will be validated according to the set locale. And if the optional format option is set this format is used for the validation. for details about the optional parameters see Zend_Date::isDate(). Db_RecordExists and Db_NoRecordExistsZend_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. Basic usageAn example of basic usage of the validators:
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.
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 recordsZend_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
The above example will check the table to ensure no records other
than the one where
You can also provide a string to the exclude clause so you can use
an operator other than
The above example will check the Database AdaptersYou 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:
Database Schemas
You can specify a schema within your database for adapters such as
PostgreSQL and DB/2 by simply supplying an array with
DigitsReturns TRUE if and only if $value only contains digit characters. EmailAddressZend_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 usageA basic example of usage is below:
This will match the email address $email and on failure populate
Options for validating Email AddressesZend_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:
Complex local parts
Zend_Validate_EmailAddress will match any valid email address
according to RFC2822. For example, valid emails include Some obsolete email formats will not currently validate (e.g. carriage returns or a "\" character in an email address). Validating only the local partIf 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.
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 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:
Checking if the hostname actually accepts emailJust 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.
Alternatively you can either pass TRUE or
FALSE to 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().
Warning
Performance warningYou 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.
Validating International Domains NamesZend_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.
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 DomainsBy 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.
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 messagesZend_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.
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. FloatReturns TRUE if and only if $value is a floating-point value. Since Zend Framework 1.8 this validator takes into account the actual locale from browser, environment or application wide set locale. You can of course use the get/setLocale accessors to change the used locale or give it while creating a instance of this validator. GreaterThanReturns TRUE if and only if $value is greater than the minimum boundary. HexZend_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.
HostnameZend_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. Basic usage A basic example of usage is below:
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, and ALLOW_ALL to allow all three types. To just check for IP addresses you can use the example below:
As well as using ALLOW_ALL to accept all 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:
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. 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.
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. 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.
Please note TLDs are only validated if you allow DNS hostnames to be validated. IbanReturns TRUE if and only if $value contains a valid IBAN (International Bank Account Number). IBAN numbers are validated against the country where they are used and by a checksum. There are two ways to validate IBAN numbers. As first way you can give a locale which represents a country. Any given IBAN number will then be validated against this country.
This should be done when you want to validate IBAN numbers for a single countries. The simpler way of validation is not to give a locale like shown in the next example.
But this shows one big problem: When you have to accept only IBAN numbers from one single country, for example france, then IBAN numbers from other countries would also be valid. Therefor just remember: When you have to validate a IBAN number against a defined country you should give the locale. And when you accept all IBAN numbers regardless of any country omit the locale for simplicity. IdenticalZend_Validate_Identical allows you to validate if a given value is identical with an set haystack. Basic usageTo validate if two values are identical you need to set the origin value as haystack. See the following example which validates two strings.
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 objectsOf 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.
ConfigurationAs 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.
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. InArrayZend_Validate_InArray allows you to validate if a given value is contained within an array. It is also able to validate multidimensional arrays. Simple array validationThe simplest way, is just to give the array which should be searched against at initiation:
This will behave exactly like PHP's in_array() method.
Of course you can give the array to validate against also afterwards by using the setHaystack() method. getHaystack() returns the actual set haystack array.
Strict array validationAs 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: 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.
Recursive array validationIn 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.
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.
IntReturns TRUE if and only if $value is a valid integer. Since Zend Framework 1.8 this validator takes into account the actual locale from browser, environment or application wide set locale. You can of course use the get/setLocale accessors to change the used locale or give it while creating a instance of this validator. IpZend_Validate_Ip allows you to validate if a given value is an IP address. It supports the IPv4 and also the IPv6 standard. Basic usageA basic example of usage is below:
Validate IPv4 or IPV6 aloneSometimes 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.
IsbnZend_Validate_Isbn allows you to validate an ISBN-10 or ISBN-13 value. Basic usageA basic example of usage is below:
This will validate any ISBN-10 and ISBN-13 without separator. Setting an explicit ISBN validation typeAn example of an ISBN type restriction is below:
The above will validate only ISBN-13 values. Valid types include:
Specifying a separator restrictionAn example of separator restriction is below:
Valid separators include:
LessThanReturns TRUE if and only if $value is less than the maximum boundary. NotEmptyThis 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. Default behaviour for Zend_Validate_NotEmptyBy 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.
Changing behaviour for Zend_Validate_NotEmptySome 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:
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:
You can also provide an instance of Zend_Config to set the desired types. To set types after instantiation, use the setType() method. PostCodeZend_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).
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.
You can also change the locale afterwards by calling setLocale(). And of course you can get the actual used locale by calling getLocale().
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().
Constructor optionsAt 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.
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.
RegexReturns TRUE if and only if $value matches against a regular expression pattern. Sitemap ValidatorsThe following validators conform to the » Sitemap XML protocol. Sitemap_ChangefreqValidates 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_LastmodValidates 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
Sitemap_LocValidates 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_PriorityValidates 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
StringLengthReturns TRUE if and only if the string length of $value is at least a minimum and no greater than a maximum (when the max option is not NULL). The setMin() method throws an exception if the minimum length is set to a value greater than the set maximum length, and the setMax() method throws an exception if the maximum length is set to a value less than the set minimum length. This class supports UTF-8 and other character encodings, based on the current value of » iconv.internal_encoding. If you need a different encoding you can set it with the accessor methods getEncoding and setEncoding.
|