anterior  
índice  
siguiente  
Updated 2012-10-02 - Version ZF 2.0.3

Clases de Validación Estándar

Zend Framework viene con un conjunto estándar de clases de validación listas para usar.

Alnum

Devuelve TRUE si y sólo si $valor contiene caracteres alfanuméricos únicamente. Este validador incluye una opción para considerar también al espacio en blanco como caracter válido.

Nota

Los caracteres alfabéticos significan caracteres que componen palabras en cada idioma. Sin embargo, el alfabeto inglés es tratado como caracteres alfabéticos en los siguientes idiomas: chino, japonés, coreano. El lenguaje es especificado por Zend_Locale.

Alpha

Devuelve TRUE si y sólo si $valor sólo contiene caracteres alfabéticos. Este validador incluye una opción para considerar también al espacio en blanco como caracter válido.

Barcode

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

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

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

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

  • CODE128: CODE128 is a high density barcode.

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

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

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

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

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

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

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

  • CODE39EXT: CODE39EXT is an extension of CODE39.

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

  • CODE93: CODE93 is the successor of CODE39.

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

  • CODE93EXT: CODE93EXT is an extension of CODE93.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • INTELLIGENTMAIL: Intelligent Mail is a postal barcode.

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

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

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

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

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

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

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

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

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

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

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

  • ROYALMAIL: Royalmail is used by Royal Mail.

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

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

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

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

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

  • UPCE: UPCE is the short variant from UPCA.

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

Supported options for Zend\Validator\Barcode

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

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

Basic usage

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

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

Optional checksum

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

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

Nota

Reduced security by disabling checksum validation

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

Writing custom adapters

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

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

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

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

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

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

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

Between

Devuelve TRUE si y sólo si $valor está entre los valores límites mínimo y máximo. La comparación es inclusiva por defecto ($valor puede ser igual a una valor límite), aunque esto puede ser anulado a fin de hacer una comparación estricta, donde $valor debe ser estrictamente mayor al mínimo y estrictamente menor al máximo.

Callback

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

Supported options for Zend\Validator\Callback

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

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

Basic usage

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

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

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

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

Usage with closures

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

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

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

Usage with class-based callbacks

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

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

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

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

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

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

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

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

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

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

Adding options

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

Consider the following class and method definition:

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

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

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

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

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

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

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

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

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

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

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

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

CreditCard

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

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

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

The following issuing institutes are accepted:

  • American Express

    China UnionPay

    Diners Club Card Blanche

    Diners Club International

    Diners Club US & Canada

    Discover Card

    JCB

    Laser

    Maestro

    MasterCard

    Solo

    Visa

    Visa Electron

Nota

Invalid institutes

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

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

Supported options for Zend\Validator\CreditCard

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

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

Basic usage

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

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

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

Accepting defined credit cards

Sometimes it is necessary to accept only defined credit card institutes instead of all; e.g., when you have a webshop which accepts only Visa and American Express cards. Zend\Validator\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
2
3
$valid = new Zend\Validator\CreditCard(
    Zend\Validator\CreditCard::AMERICAN_EXPRESS
);

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

1
2
3
4
$valid = new Zend\Validator\CreditCard(array(
    Zend\Validator\CreditCard::AMERICAN_EXPRESS,
    Zend\Validator\CreditCard::VISA
));

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

1
2
3
$valid = new Zend\Validator\CreditCard(array(
    'type' => array(Zend\Validator\CreditCard::AMERICAN_EXPRESS)
));
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
2
3
4
5
$valid = new Zend\Validator\CreditCard();
$valid->setType(array(
    Zend\Validator\CreditCard::AMERICAN_EXPRESS,
    Zend\Validator\CreditCard::VISA
));

Nota

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\Validator\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 add on for Zend\Validator\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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Your service class
class CcService
{
    public function checkOnline($cardnumber, $types)
    {
        // some online validation
    }
}

// The validation
$service = new CcService();
$valid   = new Zend\Validator\CreditCard(Zend\Validator\CreditCard::VISA);
$valid->setService(array($service, 'checkOnline'));

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

Ccnum

Devuelve TRUE si y sólo si $valor sigue el algoritmo Luhn (mod-10 checksum) para tarjetas de crédito.

Nota

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

Date

Devuelve TRUE si y sólo si $valor es una fecha válida en el formato YYYY-MM-DD (AAAA-MM-DD). Si se usa la opción locale entonces la fecha será validada de acuerdo a lo establecido para ese locale. Además, si se establece la opción format ese formato se utiliza para la validación. Para más detalles acerca de los parámetros opcionales ver en: Zend_Date::isDate().

Db\RecordExists and Db\NoRecordExists

Zend\Validator\Db\RecordExists and Zend\Validator\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\Validator\Db_*

The following options are supported for Zend\Validator\Db\NoRecordExists and Zend\Validator\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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
//Check that the email address exists in the database
$validator = new Zend\Validator\Db\RecordExists(
    array(
        'table' => 'users',
        'field' => '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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
//Check that the username is not present in the database
$validator = new Zend\Validator\Db\NoRecordExists(
    array(
        'table' => 'users',
        'field' => '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\Validator\Db\RecordExists and Zend\Validator\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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Check no other users have the username
$user_id   = $user->getId();
$validator = new Zend\Validator\Db\NoRecordExists(
    array(
        'table' => 'users',
        'field' => 'username',
        'exclude' => 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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
$email     = 'user@example.com';
$clause    = $db->quoteInto('email = ?', $email);
$validator = new Zend\Validator\Db\RecordExists(
    array(
        'table'   => 'users',
        'field'   => 'username',
        'exclude' => $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 ‘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
2
3
4
5
6
7
$validator = new Zend\Validator\Db\RecordExists(
    array(
        'table' => 'users',
        'field' => 'id',
        'adapter' => $dbAdapter
    )
);

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
2
3
4
5
6
7
$validator = new Zend\Validator\Db\RecordExists(
    array(
        'table'  => 'users',
        'schema' => 'my',
        'field'  => 'id'
    )
);

Digits

Devuelve TRUE si y sólo si $valor contiene solamente dígitos.

Dirección de Email

Zend_Validate_EmailAddress Le permite validar una dirección de email. El validador primero divide la dirección de email en la parte local @ nombre de host e intenta igualar a estos contra especificaciones conocidas para direcciones y nombres de host para el correo electrónico.

Utilización básica

Un ejemplo básico de uso se ve a continuación:

1
2
3
4
5
6
7
8
9
$validator = new Zend_Validate_EmailAddress();
if ($validator->isValid($email)) {
    // El email parece ser válido
} else {
    // El email es inválido; muestre las razones
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

Esto coincide con el correo electrónico $email y si fracasa, alimenta $validator->getMessages() con mensajes de error útiles.

>Partes locales complejas

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.
  • 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.
  • 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.
1
2
$validator = new Zend_Validate_EmailAddress();
$validator->setOptions(array('domain' => false));

Complex local parts

Zend_Validate_EmailAddress se comparará con cualquier dirección de correo válida de acuardo a RFC2822. Por ejemplo, correos electrónicos válidos incluyen bob@domain.com, bob+jones@domain.us, “bob@jones”@domain.com y “bob jones”@domain.com

Algunos formatos obsoletos de email actualmente no validan (por ejemplo los retornos de carro o “\” un caracter en una dirección de correo electrónico).

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
2
$validator = new Zend_Validate_EmailAddress();
$validator->setOptions(array('domain' => FALSE));

Validating different types of hostnames

La parte nombre de host de una dirección de correo es validado contra Zend_Validate_Hostname. Por defecto sólo son aceptados nombres de host DNS de la forma domain.com, aunque si lo desea también puede aceptar direcciones IP y nombres de host locales.

Para ello necesita instanciar a Zend_Validate_EmailAddress pasando un parámetro para indicar el tipo de nombres de host que quiere aceptar. Más detalles están incluidos en Zend_Validate_EmailAddress, aunque abajo hay un ejemplo de cómo aceptar tanto nombres de host DNS y locales:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$validator = new Zend_Validate_EmailAddress(
                    Zend_Validate_Hostname::ALLOW_DNS |
                    Zend_Validate_Hostname::ALLOW_LOCAL);
if ($validator->isValid($email)) {
    // email parece ser válido
} else {
    // email es inválido; muestre las razones
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

Verificar si el nombre de host realmente acepta email

Sólo porque una dirección de correo electrónico está en el formato correcto, no necesariamente significa que esa dirección de correo electrónico existe realmente. Para ayudar a resolver este problema, puede usar la validación MX para comprobar si existe una entrada MX (email) en el registro DNS para correo electrónico en ese nombre de host. Esto le dice que el nombre de host acepta email, pero no le dice si la dirección de correo electrónico exacta es válida en si misma.

La comprobación MX no está activada por defecto y en este momento es soportada sólo por plataformas UNIX. Para habilitar el control MX puede pasar un segundo parámetro al constructor Zend_Validate_EmailAddress.

1
2
3
4
5
6
$validator = new Zend_Validate_EmailAddress(
    array(
        'allow' => Zend_Validate_Hostname::ALLOW_DNS,
        'mx'    => true
    )
);

Nota

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.

Alternativamente, para activar o desactivar la validación MX puede pasar TRUE o FALSE a $validator->setValidateMx().

Al habilitarlo, se usarán las funciones de red para comprobar la presencia de un registro MX en el nombre de host de la dirección de correo electrónico que desea validar. Tenga en cuenta esto probablemente hará más lento su script.

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
2
3
4
5
6
7
$validator = new Zend_Validate_EmailAddress(
    array(
        'allow' => Zend_Validate_Hostname::ALLOW_DNS,
        'mx'    => true,
        'deep'  => true
    )
);

Advertencia

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.

Nota

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 también comparará caracteres internationales que existen en algunos dominios. Esto se conoce como soporte de International Domain Name (IDN). Está activado por defecto, aunque puede deshabilitarlo internamente cambiando el ajuste a través del objeto Zend_Validate_Hostname que existe en Zend_Validate_EmailAddress.

1
$validator->getHostnameValidator()->setValidateIdn(false);

Sobre el uso de setValidateIdn() encontrará más información en la documentación de Zend_Validate_Hostname.

Tenga en cuenta que los IDNs se validarán solo si usted permite que nombres de host DNS sean validados.

Validación de dominios de nivel superior

Por defecto, un nombre de host se cotejará con una lista conocida de TLDs. Está activado por defecto, aunque puede deshabilitarlo cambiando el ajuste a través del objeto interno Zend_Validate_Hostname que existe en Zend_Validate_EmailAddress.

1
$validator->getHostnameValidator()->setValidateTld(false);

Encontrará más información sobre el uso de setValidateTld() en la documentación de Zend_Validate_Hostname.

Tenga en cuenta que los TLDs se validarán solo si usted permite que nombres de host DNS sean validados.

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
2
3
4
5
6
$validator = new Zend_Validate_EmailAddress();
$validator->setMessages(
    array(
        Zend_Validate_Hostname::UNKNOWN_TLD => 'I don't know the TLD you gave'
    )
);

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

Devuelve TRUE si y sólo si $value es un valor de punto flotante. Desde Zend Framework 1.8 toma en cuenta la localizacion actual del navegador, las variables o el uso. Puede usar get/setLocale para cambiar la configuracion regional o crear una instancia para este validador

GreaterThan

Devuelve TRUE si y sólo si $valor es mayor al límite mínimo.

Hex

Devuelve TRUE si y sólo si $valor contiene caracteres hexadecimales (0-9 y A-F).

Hostname (Nombre de Host)

Zend_Validate_Hostname le permite validar un nombre de host contra una serie de especificaciones conocidas. Es posible comprobar por tres diferentes tipos de nombres: el DNS Hostname (domain.com por ejemplo), dirección IP (es decir 1.2.3.4), y nombres de host locales (localhost, por ejemplo). Por defecto sólo se comprobarán nombres de host DNS.

Uso básico

El siguiente es un ejemplo de uso básico:

1
2
3
4
5
6
7
8
9
$validator = new Zend_Validate_Hostname();
if ($validator->isValid($hostname)) {
    // hostname parece ser válido
} else {
    // hostname es inválido; muestre las razones
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

Comprobará el nombre de host $hostname y si fracasa alimentará a getMessages() con mensajes de error.

Validar diferentes tipos de nombres de host

También se puede encontrar coincidencias de direcciones IP, nombres de host locales, o una combinación de todos los tipos permitidos. Esto puede hacerse pasando un parámetro a Zend_Validate_Hostname cuando lo instancia. El parámetro debe ser un entero que determina qué tipos de nombres de host están permitidos. Se recomienda el uso de las constantes de Zend_Validate_Hostname para hacerlo.

Las constantes de Zend_Validate_Hostname son: ALLOW_DNS para permitir sólo nombres de host DNS, ALLOW_IP para permitir direcciones IP, ALLOW_LOCAL para permitir nombres de host de la red local, y ALLOW_ALL para permitir todos estos tres tipos. Para comprobar que direcciones IP puede utilizar, vea el siguiente ejemplo:

1
2
3
4
5
6
7
8
9
$validator = new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_IP);
if ($validator->isValid($hostname)) {
    // hostname parece ser válido
} else {
    // hostname es inválido; muestre las razones
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

Usando ALLOW_ALL para aceptar todos los tipos de nombres de host, también puede combinar estos tipos para realizar combinaciones. Por ejemplo, para aceptar nombres de host DNS y locales, instancie el objeto Zend_Validate_Hostname como:

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

Validación de Nombres de Dominio Internacionales

Algunos (ccTLD), es decir países “Country Code Top Level Domains” , como ‘de’ (Alemania), aceptan caracteres internacionales como nombres de dominio. Estos son conocidos como Nombres de Dominio Internacionales (IDN, por sus siglas en inglés). Se puede buscar una coincidencia de estos dominios con Zend_Validate_Hostname, a través de caracteres extendidos que se utilizan en el proceso de validación.

Until now more than 50 ccTLDs support IDN domains.

Cotejar dominios IDN es tan simple como usar el validador estándar Hostname, ya que este viene habilitado por defecto. Si desea desactivar la validación IDN, se puede hacer ya sea pasando un parámetro al constructor Zend_Validate_Hostname o a través del método setValidateIdn().

Puede deshabilitar la validación IDN, pasando un segundo parámetro al constructor Zend_Validate_Hostname de la siguiente manera.

1
2
3
4
5
6
7
$validator =
    new Zend_Validate_Hostname(
        array(
            'allow' => Zend_Validate_Hostname::ALLOW_DNS,
            'idn'   => false
        )
    );

Alternativamente puede pasar TRUE o FALSE a setValidateIdn() para activar o desactivar la validación IDN. Si está tratando de cotejar un nombre de host IDN que actualmente no está soportado, es probable que falle la validación si tiene caracteres internacionales en el nombre de host. Cuando un archivo ccTLD no existe en Zend/Validate/Hostname, especificando los caracteres adicionales se puede realizar una validación normal.

Tenga en cuenta que una validación IDN solo se realizará si tiene habilidada la validación para nombres de host DNS.

Validacuión de dominios de nivel superior

Por defecto un nombre de host se cotejará con una lista de TLDs conocidos. Si esta funcionalidad no es necesaria, puede ser desactivada en la misma forma que deshabilita el soporte IDN. Puede deshabilitar la validación TLD pasando un tercer parámetro al constructor Zend_Validate_Hostname. En el siguiente ejemplo estamos dando respaldo a la validación IDN a través del segundo parámetro.

1
2
3
4
5
6
7
8
$validator =
    new Zend_Validate_Hostname(
        array(
            'allow' => Zend_Validate_Hostname::ALLOW_DNS,
            'idn'   => true,
            'tld'   => false
        )
    );

Alternativamente puede pasar TRUE o FALSE a setValidateTld() para activar o desactivar la validación TLD.

Tenga en cuenta que una validación de TLDs solo se realizará si tiene habilidada la validación para nombres de host DNS.

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$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.

1
2
3
4
5
6
7
$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

Devuelve TRUE si y sólo si $valor se encuentra en un array, y si la opción es estricta entonces también verificará el tipo de dato de $valor.

Identical

Zend\Validator\Identical allows you to validate if a given value is identical with an set haystack.

Supported options for Zend\Validator\Identical

The following options are supported for Zend\Validator\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
2
3
4
$valid = new Zend\Validator\Identical('origin');
if ($valid->isValid($value) {
    return true;
}

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\Validator\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
2
3
4
5
6
$valid = new Zend\Validator\Identical(123);
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Nota

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\Validator\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
2
3
4
5
6
$form->addElement('password', 'elementOne');
$form->addElement('password', 'elementTwo', array(
    'validators' => array(
        array('identical', false, array('token' => 'elementOne'))
    )
));

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\Validator\Identical validates tokens strict. You can change this behaviour by using the strict option. The default value for this property is TRUE.

1
2
3
4
5
6
7
$valid = new Zend\Validator\Identical(array('token' => 123, 'strict' => FALSE));
$input = '123';
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

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 convenience you can also use setStrict() and getStrict().

Configuration

As all other validators also Zend\Validator\Identical supports the usage of configuration settings as input parameter. This means that you can configure this validator with an Traversable instance.

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
2
3
4
5
6
$valid = new Zend\Validator\Identical(array('token' => 123));
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

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
2
3
4
5
6
$valid = new Zend\Validator\Identical(array('token' => array('token' => 123)));
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

InArray

Zend\Validator\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\Validator\InArray

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

  • haystack: Sets the haystack for the validation.

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

  • strict: Three modes of comparison are offered owing to an often overlooked, and potentially dangerous security issue when validating string input from user input.

    • InArray::COMPARE_STRICT

      This is a normal in_array strict comparison that checks value and type.

    • InArray::COMPARE_NOT_STRICT

      This is a normal in_array non-strict comparison that checks value only.

Advertencia

This mode may give false positives when strings are compared against ints or floats owing to in_array’s behaviour of converting strings to int in such cases. Therefore, “foo” would become 0, “43foo” would become 43, while “foo43” would also become 0.

  • InArray::COMPARE_NOT_STRICT_AND_PREVENT_STR_TO_INT_VULNERABILITY

    To remedy the above warning, this mode offers a middle-ground which allows string representations of numbers to be successfully matched against either their string or int counterpart and vice versa. For example: “0” will successfully match against 0, but “foo” would not match against 0 as would be true in the *COMPARE_NOT_STRICT* mode. This is the safest option to use when validating web input, and is the default.

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
2
3
4
5
6
$validator = new Zend\Validator\InArray(array('value1', 'value2',...'valueN'));
if ($validator->isValid('value')) {
    // value found
} else {
    // no value found
}

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

Nota

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

Alternatively, you can define the array to validate against after object construction by using the setHaystack() method. getHaystack() returns the actual set haystack array.

1
2
3
4
5
6
7
8
$validator = new Zend\Validator\InArray();
$validator->setHaystack(array('value1', 'value2',...'valueN'));

if ($validator->isValid('value')) {
    // value found
} else {
    // no value found
}

Array validation modes

As previously mentioned, there are possible security issues when using the default non-strict comparison mode, so rather than restricting the developer, we’ve chosen to offer both strict and non-strict comparisons and adding a safer middle-ground.

It’s possible to set the strict mode at initialisation and afterwards with the setStrict method. InArray::COMPARE_STRICT equates to true and InArray::COMPARE_NOT_STRICT_AND_PREVENT_STR_TO_INT_VULNERABILITY equates to false.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// defaults to InArray::COMPARE_NOT_STRICT_AND_PREVENT_STR_TO_INT_VULNERABILITY
$validator = new Zend\Validator\InArray(
    array(
         'haystack' => array('value1', 'value2',...'valueN'),
    )
);

// set strict mode
$validator = new Zend\Validator\InArray(
    array(
         'haystack' => array('value1', 'value2',...'valueN'),
         'strict'   => InArray::COMPARE_STRICT  // equates to ``true``
    )
);

// set non-strict mode
$validator = new Zend\Validator\InArray(
    array(
         'haystack' => array('value1', 'value2',...'valueN'),
         'strict'   => InArray:COMPARE_NOT_STRICT  // equates to ``false``
    )
);

// or

$validator->setStrict(InArray::COMPARE_STRICT);
$validator->setStrict(InArray::COMPARE_NOT_STRICT);
$validator->setStrict(InArray::COMPARE_NOT_STRICT_AND_PREVENT_STR_TO_INT_VULNERABILITY);

Nota

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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
$validator = new Zend\Validator\InArray(
    array(
        'haystack' => array(
            'firstDimension' => array('value1', 'value2',...'valueN'),
            'secondDimension' => array('foo1', 'foo2',...'fooN')),
        'recursive' => true
    )
);

if ($validator->isValid('value')) {
    // value found
} else {
    // no value found
}

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
$validator = new Zend\Validator\InArray(
    array(
        'firstDimension' => array('value1', 'value2',...'valueN'),
        'secondDimension' => array('foo1', 'foo2',...'fooN')
    )
);

$validator->setRecursive(true);

if ($validator->isValid('value')) {
    // value found
} else {
    // no value found
}

Nota

Default setting for recursion

Per default the recursive validation is turned off.

Nota

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

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

Zend\Validator\Ip allows you to validate if a given value is an IP address. It supports the IPv4, IPv6 and IPvFeature definitions.

Supported options for Zend\Validator\Ip

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

  • allowipv4: Defines if the validator allows IPv4 addresses. This option defaults to TRUE.
  • allowipv6: Defines if the validator allows IPv6 addresses. This option defaults to TRUE.
  • allowipvfuture: Defines if the validator allows IPvFuture addresses. This option defaults to false.
  • allowliteral: Defines if the validator allows IPv6 or IPvFuture with URI literal style (the IP surrounded by brackets). This option defaults to true.

Basic usage

A basic example of usage is below:

1
2
3
4
5
6
$validator = new Zend\Validator\Ip();
if ($validator->isValid($ip)) {
    // ip appears to be valid
} else {
    // ip is invalid; print the reasons
}

Nota

Invalid IP addresses

Keep in mind that Zend\Validator\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.

Nota

IPv6/IPvFuture validation

Zend\Validator\Ip validates IPv6/IPvFuture 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\Validator\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
2
3
4
5
6
$validator = new Zend\Validator\Ip(array('allowipv6' => false));
if ($validator->isValid($ip)) {
    // ip appears to be valid ipv4 address
} else {
    // ip is no ipv4 address
}

Nota

Default behaviour

The default behaviour which Zend\Validator\Ip follows is to allow both standards.

Isbn

Zend\Validator\Isbn allows you to validate an ISBN-10 or ISBN-13 value.

Supported options for Zend\Validator\Isbn

The following options are supported for Zend\Validator\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\Validator\Isbn::AUTO. For details take a look at this section.

Basic usage

A basic example of usage is below:

1
2
3
4
5
6
$validator = new Zend\Validator\Isbn();
if ($validator->isValid($isbn)) {
    // isbn is valid
} else {
    // isbn is not valid
}

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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$validator = new Zend\Validator\Isbn();
$validator->setType(Zend\Validator\Isbn::ISBN13);
// OR
$validator = new Zend\Validator\Isbn(array(
    'type' => Zend\Validator\Isbn::ISBN13,
));

if ($validator->isValid($isbn)) {
    // this is a valid ISBN-13 value
} else {
    // this is an invalid ISBN-13 value
}

The above will validate only ISBN-13 values.

Valid types include:

  • Zend\Validator\Isbn::AUTO (default)
  • Zend\Validator\Isbn::ISBN10
  • Zend\Validator\Isbn::ISBN13

Specifying a separator restriction

An example of separator restriction is below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$validator = new Zend\Validator\Isbn();
$validator->setSeparator('-');
// OR
$validator = new Zend\Validator\Isbn(array(
    'separator' => '-',
));

if ($validator->isValid($isbn)) {
    // this is a valid ISBN with separator
} else {
    // this is an invalid ISBN with separator
}

Nota

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

Devuelve TRUE si y sólo si $valor es menor al límite máximo.

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\Validator\NotEmpty

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

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

Default behaviour for Zend\Validator\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
2
3
4
$valid = new Zend\Validator\NotEmpty();
$value  = '';
$result = $valid->isValid($value);
// returns false

Nota

Default behaviour differs from PHP

Without providing configuration, Zend\Validator\NotEmpty‘s behaviour differs from PHP.

Changing behaviour for Zend\Validator\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 accommodate differing needs, Zend\Validator\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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// Returns false on 0
$validator = new Zend\Validator\NotEmpty(Zend\Validator\NotEmpty::INTEGER);

// Returns false on 0 or '0'
$validator = new Zend\Validator\NotEmpty(
    Zend\Validator\NotEmpty::INTEGER + Zend\Validator\NotEmpty::ZERO
);

// Returns false on 0 or '0'
$validator = new Zend\Validator\NotEmpty(array(
    Zend\Validator\NotEmpty::INTEGER,
    Zend\Validator\NotEmpty::ZERO
));

// Returns false on 0 or '0'
$validator = new Zend\Validator\NotEmpty(array(
    'integer',
    'zero',
));

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

PostCode

Zend\Validator\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\Validator\PostCode knows more than 160 different postal code formats. 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\Validator\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
$validator = new Zend\Validator\PostCode('de_AT');

When you don’t set a locale yourself, then Zend\Validator\PostCode will use the application wide set locale, or, when there is none, the locale returned by Locale.

1
2
3
4
// application wide locale within your bootstrap
Locale::setDefault('de_AT');

$validator = new Zend\Validator\PostCode();

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

1
2
$validator = new Zend\Validator\PostCode('de_AT');
$validator->setLocale('en_GB');

Postal code formats 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
2
$validator = new Zend\Validator\PostCode('de_AT');
$validator->setFormat('AT-\d{5}');

Nota

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 a string representing a fully qualified locale to the constructor of Zend\Validator\PostCode.

1
2
$validator = new Zend\Validator\PostCode('de_AT');
$validator = new Zend\Validator\PostCode($locale);

Additionally, you may pass either an array or a Traversable instance 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
2
3
4
$validator = new Zend\Validator\PostCode(array(
    'locale' => 'de_AT',
    'format' => 'AT_\d+'
));

Supported options for Zend\Validator\PostCode

The following options are supported for Zend\Validator\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

Devuelve TRUE si y sólo si $valor coincide con el patrón de una expresión regular.

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.

Sitemap Lastmod Validator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$validator = new Zend\Validator\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\Uri\Uri::isValid() 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.

Sitemap Priority Validator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$validator = new Zend\Validator\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

Supported options for Zend\Validator\Sitemap_*

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

StringLength

Devuelve TRUE si y sólo si la longitud del string $valor es por lo menos un mínimo y no mayor a un máximo (cuando la opción max no es NULL). Desde la versión 1.5.0, el método setMin() lanza una excepción si la longitud mínima tiene un valor mayor que la longitud máxima establecida, y el método setMax() lanza una excepción si la longitud máxima se fija a un valor inferior que la longitud mínima establecida. Desde la versión 1.0.2, esta clase soporta UTF-8 y a otras codificaciones, basado en el valor actual de: iconv.internal_encoding. If you need a different encoding you can set it with the accessor methods getEncoding and setEncoding.

|

Contenidos

Tema anterior

Introducción

Próximo tema

Cadenas de Validadores

Esta página

Nota: Es necesario estar conectado a tu cuenta GitHub para contribuir a la documentación.

Edit this document

Edit this document

The source code of this file is hosted on GitHub. Everyone can update and fix errors in this document with few clicks - no downloads needed.

  1. Login with your GitHub account.
  2. Go to Clases de Validación Estándar on GitHub.
  3. Edit file contents using GitHub's text editor in your web browser
  4. Fill in the Commit message text box at the end of the page telling why you did the changes. Press Propose file change button next to it when done.
  5. On Send a pull request page you don't need to fill in text anymore. Just press Send pull request button.
  6. Your changes are now queued for review under project's Pull requests tab on GitHub.