Previous Next

Standard Validation Classes

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

Alnum

Returns 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.

Note:

The alphabetic characters mean characters that makes up words in each language. However, the English alphabet is treated as the alphabetic characters in following languages: Chinese, Japanese, Korean. The language is specified by Zend_Locale.

Alpha

Returns true if and only if $value contains only alphabetic characters. This validator includes an option to also consider white space characters as valid.

Barcode

This validator is instantiated with a barcode type against which you wish to validate a barcode value. It currently supports "UPC-A" (Universal Product Code) and "EAN-13" (European Article Number) barcode types, and the isValid() method returns true if and only if the input successfully validates against the barcode validation algorithm. You should remove all characters other than the digits zero through nine (0-9) from the input value before passing it on to the validator.

Between

Returns 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.

Ccnum

Returns true if and only if $value follows the Luhn algorithm (mod-10 checksum) for credit card numbers.

Date

Returns 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_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.

Basic usage

An example of basic usage of the validators:

//Check that the email address exists in the database
$validator = new Zend_Validate_Db_RecordExists('users', 'emailaddress');
if ($validator->isValid($emailaddress)) {
    // email address appears to be valid
} else {
    // email address is invalid; print the reasons
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

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.

//Check that the username is not present in the database
$validator = new Zend_Validate_Db_NoRecordExists('users', 'username');
if ($validator->isValid($username)) {
    // username appears to be valid
} else {
    // username is invalid; print the reason
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}

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)

//Check no other users have the username
$user_id   = $user->getId();
$validator = new Zend_Validate_Db_NoRecordExists(
    'users',
    'username',
    array(
        'field' => 'id',
        'value' => $user_id
    )
);

if ($validator->isValid($username)) {
    // username appears to be valid
} else {
    // username is invalid; print the reason
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}

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.

$post_id   = $post->getId();
$clause    = $db->quoteInto('post_id = ?', $category_id);
$validator = new Zend_Validate_Db_RecordExists(
    'posts_categories',
    'post_id',
    $clause
);

if ($validator->isValid($username)) {
    // username appears to be valid
} else {
    // username is invalid; print the reason
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}

The above example will check the posts_categories table to ensure that a record with the post_id has a value matching $category_id

Database Adapters

You can also specify an adapter, as the fourth parameter when instantiating your validator, 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:

$validator = new Zend_Validate_Db_RecordExists('users', 'id', null, $dbAdapter);

Digits

Returns true if and only if $value only contains digit characters.

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:

$validator = new Zend_Validate_EmailAddress();
if ($validator->isValid($email)) {
    // email appears to be valid
} else {
    // email is invalid; print the reasons
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}
This will match the email address $email and on failure populate $validator->getMessages() with useful error messages.

Complex local parts

Zend_Validate_EmailAddress will match any valid email address according to RFC2822. For example, valid emails include bob@domain.com, bob+jones@domain.us, "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 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:

$validator = new Zend_Validate_EmailAddress(
                    Zend_Validate_Hostname::ALLOW_DNS |
                    Zend_Validate_Hostname::ALLOW_LOCAL);
if ($validator->isValid($email)) {
    // email appears to be valid
} else {
    // email is invalid; print the reasons
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

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 and at this time is only supported by UNIX platforms. To enable MX checking you can pass a second parameter to the Zend_Validate_EmailAddress constructor.

$validator = new Zend_Validate_EmailAddress(Zend_Validate_Hostname::ALLOW_DNS,
                                            true);
Alternatively you can either pass true or false to $validator->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.

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.

$validator->hostnameValidator->setValidateIdn(false);
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.

$validator->hostnameValidator->setValidateTld(false);
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.

Float

Returns 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.

GreaterThan

Returns true if and only if $value is greater than the minimum boundary.

Hex

Returns true if and only if $value contains only hexadecimal digit characters.

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.

Basic usage

A basic example of usage is below:

$validator = new Zend_Validate_Hostname();
if ($validator->isValid($hostname)) {
    // hostname appears to be valid
} else {
    // hostname is invalid; print the reasons
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}
This will match the hostname $hostname and on failure populate $validator->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, and ALLOW_ALL to allow all three types. To just check for IP addresses you can use the example below:

$validator = new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_IP);
if ($validator->isValid($hostname)) {
    // hostname appears to be valid
} else {
    // hostname is invalid; print the reasons
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

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:

$validator = new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_DNS |
                                        Zend_Validate_Hostname::ALLOW_IP);

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.

At present the list of supported ccTLDs include:

  • at (Austria)

  • ch (Switzerland)

  • li (Liechtenstein)

  • de (Germany)

  • fi (Finland)

  • hu (Hungary)

  • no (Norway)

  • se (Sweden)

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 by either passing a parameter to the Zend_Validate_Hostname constructor or via the $validator->setValidateIdn() method.

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

$validator =
    new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_DNS, false);
Alternatively you can either pass TRUE or FALSE to $validator->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.

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.

$validator =
    new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_DNS,
                               true,
                               false);
Alternatively you can either pass TRUE or FALSE to $validator->setValidateTld() to enable or disable TLD validation.

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

Iban

Returns 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.

$validator = new Zend_Validate_Iban('de_AT');
$iban = 'AT611904300234573201';
if ($validator->isValid($iban)) {
    // IBAN appears to be valid
} else {
    // IBAN is invalid
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

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.

$validator = new Zend_Validate_Iban();
$iban = 'AT611904300234573201';
if ($validator->isValid($iban)) {
    // IBAN appears to be valid
} else {
    // IBAN is invalid
}

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.

InArray

Returns true if and only if a "needle" $value is contained in a "haystack" array. If the strict option is true, then the type of $value is also checked.

Int

Returns 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.

Ip

Returns true if and only if $value is a valid IP address.

LessThan

Returns true if and only if $value is less than the maximum boundary.

NotEmpty

Returns true if and only if $value is not an empty value.

Regex

Returns true if and only if $value matches against a regular expression pattern.

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

$validator = new Zend_Validate_Sitemap_Lastmod();

$validator->isValid('1999-11-11T22:23:52-02:00'); // true
$validator->isValid('2008-05-12T00:42:52+02:00'); // true
$validator->isValid('1999-11-11'); // true
$validator->isValid('2008-05-12'); // true

$validator->isValid('1999-11-11t22:23:52-02:00'); // false
$validator->isValid('2008-05-12T00:42:60+02:00'); // false
$validator->isValid('1999-13-11'); // false
$validator->isValid('2008-05-32'); // false
$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 be a decimal between 0.0 and 1.0. This validator accepts both numeric values and string values.

Example #2 Sitemap Priority Validator

$validator = new Zend_Validate_Sitemap_Priority();

$validator->isValid('0.1'); // true
$validator->isValid('0.789'); // true
$validator->isValid(0.8); // true
$validator->isValid(1.0); // true

$validator->isValid('1.1'); // false
$validator->isValid('-0.4'); // false
$validator->isValid(1.00001); // false
$validator->isValid(0xFF); // false
$validator->isValid('foo'); // false

StringLength

Returns 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 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.

Previous Next
Introduction to Zend Framework
Overview
Installation
Zend_Acl
Introduction
Refining Access Controls
Advanced Usage
Zend_Amf
Introduction
Zend_Amf_Server
Zend_Application
Introduction
Zend_Application Quick Start
Theory of Operation
Examples
Core Functionality
Available Resource Plugins
Zend_Auth
Introduction
Database Table Authentication
Digest Authentication
HTTP Authentication Adapter
LDAP Authentication
Open ID Authentication
Zend_Cache
Introduction
The Theory of Caching
Zend_Cache Frontends
Zend_Cache Backends
Zend_Captcha
Introduction
Captcha Operation
CAPTCHA Adapters
Zend_CodeGenerator
Introduction
Zend_CodeGenerator Examples
Zend_CodeGenerator Reference
Zend_Config
Introduction
Theory of Operation
Zend_Config_Ini
Zend_Config_Xml
Zend_Config_Writer
Zend_Config_Writer
Zend_Console_Getopt
Introduction
Declaring Getopt Rules
Fetching Options and Arguments
Configuring Zend_Console_Getopt
Zend_Controller
Zend_Controller Quick Start
Zend_Controller Basics
The Front Controller
The Request Object
The Standard Router
The Dispatcher
Action Controllers
Action Helpers
The Response Object
Plugins
Using a Conventional Modular Directory Structure
MVC Exceptions
Migrating from Previous Versions
Zend_Currency
Introduction to Zend_Currency
How to Work with Currencies
Migrating from Previous Versions
Zend_Date
Introduction
Theory of Operation
Basic Methods
Zend_Date API Overview
Creation of Dates
Constants for General Date Functions
Working Examples
Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Debug
Dumping Variables
Zend_Dojo
Introduction
Zend_Dojo_Data: dojo.data Envelopes
Dojo View Helpers
Dojo Form Elements and Decorators
Zend_Dom
Introduction
Zend_Dom_Query
Zend_Exception
Using Exceptions
Zend_Feed
Introduction
Importing Feeds
Retrieving Feeds from Web Pages
Consuming an RSS Feed
Consuming an Atom Feed
Consuming a Single Atom Entry
Modifying Feed and Entry structures
Custom Feed and Entry Classes
Zend_File
Zend_File_Transfer
Validators for Zend_File_Transfer
Filters for Zend_File_Transfer
Migrating from previous versions
Zend_Filter
Introduction
Standard Filter Classes
Filter Chains
Writing Filters
Zend_Filter_Input
Zend_Filter_Inflector
Zend_Form
Zend_Form
Zend_Form Quick Start
Creating Form Elements Using Zend_Form_Element
Creating Forms Using Zend_Form
Creating Custom Form Markup Using Zend_Form_Decorator
Standard Form Elements Shipped With Zend Framework
Standard Form Decorators Shipped With Zend Framework
Internationalization of Zend_Form
Advanced Zend_Form Usage
Zend_Gdata
Introduction
Authenticating with AuthSub
Using the Book Search Data API
Authenticating with ClientLogin
Using Google Calendar
Using Google Documents List Data API
Using Google Health
Using Google Spreadsheets
Using Google Apps Provisioning
Using Google Base
Using Picasa Web Albums
Using the YouTube Data API
Catching Gdata Exceptions
Zend_Http
Introduction
Zend_Http_Client - Advanced Usage
Zend_Http_Client - Connection Adapters
Zend_Http_Cookie and Zend_Http_CookieJar
Zend_Http_Response
Zend_InfoCard
Introduction
Zend_Json
Introduction
Basic Usage
Advanced Usage of Zend_Json
XML to JSON conversion
Zend_Json_Server - JSON-RPC server
Zend_Layout
Introduction
Zend_Layout Quick Start
Zend_Layout Configuration Options
Zend_Layout Advanced Usage
Zend_Ldap
Introduction
Zend_Loader
Loading Files and Classes Dynamically
The Autoloader
Resource Autoloaders
Loading Plugins
Zend_Locale
Introduction
Using Zend_Locale
Normalization and Localization
Working with Dates and Times
Supported locales
Migrating from previous versions
Zend_Log
Overview
Writers
Formatters
Filters
Zend_Mail
Introduction
Sending via SMTP
Sending Multiple Mails per SMTP Connection
Using Different Transports
HTML E-Mail
Attachments
Adding Recipients
Controlling the MIME Boundary
Additional Headers
Character Sets
Encoding
SMTP Authentication
Securing SMTP Transport
Reading Mail Messages
Zend_Measure
Introduction
Creation of Measurements
Outputting measurements
Manipulating Measurements
Types of measurements
Zend_Memory
Overview
Memory Manager
Memory Objects
Zend_Mime
Zend_Mime
Zend_Mime_Message
Zend_Mime_Part
Zend_Navigation
Introduction
Pages
Containers
Zend_OpenId
Introduction
Zend_OpenId_Consumer Basics
Zend_OpenId_Provider
Zend_Paginator
Introduction
Usage
Configuration
Advanced usage
Zend_Pdf
Introduction
Creating and Loading PDF Documents
Save Changes to PDF Documents
Working with Pages
Drawing
Document Info and Metadata.
Zend_Pdf module usage example
Zend_ProgressBar
Zend_ProgressBar
Zend_Reflection
Introduction
Zend_Reflection Examples
Zend_Reflection Reference
Zend_Registry
Using the Registry
Zend_Rest
Introduction
Zend_Rest_Client
Zend_Rest_Server
Zend_Search_Lucene
Overview
Building Indexes
Searching an Index
Query Language
Query Construction API
Character Set
Extensibility
Interoperating with Java Lucene
Advanced
Best Practices
Zend_Server
Introduction
Zend_Server_Reflection
Zend_Service
Introduction
Zend_Service_Akismet
Zend_Service_Amazon
Zend_Service_Amazon_Ec2
Zend_Service_Amazon_Ec2: Instances
Zend_Service_Amazon_Ec2: Windows Instances
Zend_Service_Amazon_Ec2: Reserved Instances
Zend_Service_Amazon_Ec2: CloudWatch Monitoring
Zend_Service_Amazon_Ec2: Amazon Machine Images (AMI)
Zend_Service_Amazon_Ec2: Elastic Block Stroage (EBS)
Zend_Service_Amazon_Ec2: Elastic IP Addresses
Zend_Service_Amazon_Ec2: Keypairs
Zend_Service_Amazon_Ec2: Regions and Availability Zones
Zend_Service_Amazon_Ec2: Security Groups
Zend_Service_Amazon_S3
Zend_Service_Audioscrobbler
Zend_Service_Delicious
Zend_Service_Flickr
Zend_Service_Nirvanix
Zend_Service_ReCaptcha
Zend_Service_Simpy
Introduction
Zend_Service_StrikeIron
Zend_Service_StrikeIron: Bundled Services
Zend_Service_StrikeIron: Advanced Uses
Zend_Service_Technorati
Zend_Service_Twitter
Zend_Service_Yahoo
Zend_Session
Introduction
Basic Usage
Advanced Usage
Global Session Management
Zend_Session_SaveHandler_DbTable
Zend_Soap
Zend_Soap_Server
Zend_Soap_Client
WSDL Accessor
AutoDiscovery
Zend_Tag
Introduction
Zend_Tag_Cloud
Zend_Test
Introduction
Zend_Test_PHPUnit
Zend_Text
Zend_Text_Figlet
Zend_Text_Table
Zend_TimeSync
Introduction
Working with Zend_TimeSync
Zend_Tool_Framework
Introduction
Using the CLI Tool
Architecture
Creating Providers to use with Zend_Tool_Framework
Shipped System Providers
Zend_Tool_Project
Zend_Tool_Project Introduction
Create A Project
Zend Tool Project Providers
Zend_Translate
Introduction
Adapters for Zend_Translate
Using Translation Adapters
Migrating from previous versions
Zend_Uri
Zend_Uri
Zend_Validate
Introduction
Standard Validation Classes
Validator Chains
Writing Validators
Validation Messages
Zend_Version
Getting the Zend Framework Version
Zend_View
Introduction
Controller Scripts
View Scripts
View Helpers
Zend_View_Abstract
Migrating from Previous Versions
Zend_Wildfire
Zend_Wildfire
Zend_XmlRpc
Introduction
Zend_XmlRpc_Client
Zend_XmlRpc_Server
Zend Framework Requirements
Introduction
Zend Framework Coding Standard for PHP
Overview
PHP File Formatting
Naming Conventions
Coding Style
Zend Framework Performance Guide
Introduction
Class Loading
Zend_Db Performance
Internationalization (i18n) and Localization (l10n)
View Rendering
Copyright Information