標準のバリデーションクラス群

Zend Framework には、すぐに使える標準のバリデーションクラス群が同梱されています。

Alnum(一部日本語)

Zend_Validate_Alnum により、 与えられた文字列がアルファベットおよび数字だけを含むかどうか検証できます。 検証したい入力に対する長さの制限はありません。 (訳注:ここでいうアルファベットおよび数字、とは各言語で使われる文字および数字の集合を意味します。英数字ではありません

Zend_Validate_Alnum でサポートされるオプション

下記のオプションが Zend_Validate_Alnum でサポートされます。

  • allowWhiteSpace: 空白文字が許されるかどうか。 このオプションの既定値は FALSE です。

基本的な使用法

下記は基本的な使用例です。

$validator = new Zend_Validate_Alnum();
if ($validator->isValid('Abcd12')) {
    // value contains only allowed chars
} else {
    // false
}

空白を使用

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

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

$validator = new Zend_Validate_Alnum(array('allowWhiteSpace' => true));
if ($validator->isValid('Abcd and 12')) {
    // value contains only allowed chars
} else {
    // false
}

別の言語を使用

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

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

実際には、それらの固有の文書で受け付けられない3つの言語があります。 それらの言語は、Korean日本語中国語です。 because this languages are using an alphabet where a single character is build by using multiple characters.

これらの言語を使用する場合、入力は英語のアルファベットを使用した検証のみ行なわれます。

Alpha(一部日本語)

Zend_Validate_Alpha により、 与えられた文字列がアルファベットだけを含むかどうか検証できます。 検証したい入力に対する長さの制限はありません。 このバリデータは数字を受け付けませんが、 Zend_Validate_Alnum と関係があります。 (訳注:ここでいうアルファベット、とはアラビア文字やタイ文字、キリール文字など、各言語で使われる文字の集合を意味します。英字とは限りません

Zend_Validate_Alpha でサポートされるオプション

下記のオプションが Zend_Validate_Alpha でサポートされます。

  • allowWhiteSpace: 空白文字が許されるかどうか。 このオプションの既定値は FALSE です。

基本的な使用法

下記は基本的な使用例です。

$validator = new Zend_Validate_Alpha();
if ($validator->isValid('Abcd')) {
    // value contains only allowed chars
} else {
    // false
}

空白を使用

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

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

$validator = new Zend_Validate_Alpha(array('allowWhiteSpace' => true));
if ($validator->isValid('Abcd and efg')) {
    // value contains only allowed chars
} else {
    // false
}

別の言語を使用

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

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

実際には、それらの固有の文書で受け付けられない3つの言語があります。 それらの言語は、Korean日本語中国語です。 because this languages are using an alphabet where a single character is build by using multiple characters.

これらの言語を使用する場合、入力は英語のアルファベットを使用した検証のみ行なわれます。

Barcode

Zend_Validate_Barcode allows you to check if a given value can be represented as barcode.

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

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

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

  • CODE25INTERLEAVED: Often called "Code 2 of 5 Interleaved".

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

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

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

  • CODE39EXT: CODE39EXT is an extension of CODE39.

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

  • CODE93: CODE93 is the successor of CODE39.

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

  • CODE93EXT: CODE93EXT is an extension of CODE93.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • INTELLIGENTMAIL: Intelligent Mail is a postal barcode.

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

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

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

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

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

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

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

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

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

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

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

  • ROYALMAIL: Royalmail is used by Royal Mail.

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

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

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

  • UPCA: UPC is the shortcut for "Univeral Product Code".

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

  • UPCE: UPCE is the short variant from UPCA.

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

Supported options for Zend_Validate_Barcode

The following options are supported for Zend_Validate_Barcode:

  • adapter: Sets the barcode adapter which will be used. Supported are all above noted adapters. When using a self defined adapter, then you have to set the complete classname.

  • checksum: TRUE when the barcode should contain a checksum. The default value depends on the used adapter. Note that some adapters don't allow to set this option.

  • options: Defines optional options for a self written adapters.

Basic usage

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

$valid = new Zend_Validate_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.

$valid = new Zend_Validate_Barcode(array(
    'adapter'  => 'EAN13',
    'checksum' => false,
));
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Reduced security by disabling checksum validation

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

Writing custom adapters

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

  • Length: The length your barcode must have. It can have one of the following values:

    • Integer: A value greater 0, which means that the barcode must have this length.

    • -1: There is no limitation for the length of this barcode.

    • "even": The length of this barcode must have a even amount of digits.

    • "odd": The length of this barcode must have a odd amount of digits.

    • array: An array of integer values. The length of this barcode must have one of the set array values.

  • Characters: A string which contains all allowed characters for this barcode. Also the integer value 128 is allowed, which means the first 128 characters of the ASCII table.

  • Checksum: A string which will be used as callback for a method which does the checksum validation.

Your custom barcode validator must extend Zend_Validate_Barcode_AdapterAbstract or implement Zend_Validate_Barcode_AdapterInterface.

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

class My_Barcode_MyBar extends Zend_Validate_Barcode_AdapterAbstract
{
    protected $_length     = 'even';
    protected $_characters = '0123456789ABCDE';
    protected $_checksum   = '_mod66';

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

$valid = new Zend_Validate_Barcode('My_Barcode_MyBar');
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Between

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

Zend_Validate_Between supports only number validation

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

Supported options for Zend_Validate_Between

The following options are supported for Zend_Validate_Between:

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

  • max: Sets the maximum border for the validation.

  • min: Sets the minimum border for the validation.

Default behaviour for Zend_Validate_Between

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

$valid  = new Zend_Validate_Between(array('min' => 0, 'max' => 10));
$value  = 10;
$result = $valid->isValid($value);
// returns true

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

Validation exclusive the border values

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

$valid  = new Zend_Validate_Between(
    array(
        'min' => 0,
        'max' => 10,
        'inclusive' => false
    )
);
$value  = 10;
$result = $valid->isValid($value);
// returns false

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

コールバック

Zend_Validate_Callback は 与えられた値に対してバリデートを行うコールバックを供給することができます。

Zend_Validate_Callback にてサポートされるオプション

次のオプションは Zend_Validate_Callback にてサポートされます:

  • callback: バリデーションにて 呼び出されるコールバックのセット

  • options: コールバックに 与えられる追加オプションのセット

基本的な使用法

もっとも単純なユースケースは単なる関数を持ち、コールバックとして使用します。 次の関数を持ったつもりになりましょう。

function myMethod($value)
{
    // some validation
    return true;
}

Zend_Validate_Callback内で使用するにはちょうどこの通り 呼び出さなければなりません:

$valid = new Zend_Validate_Callback('myMethod');
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

クロージャとの使用方法

PHP 5.3 は基本的には、内包あるいは 匿名 関数の 無名関数を導入しています。 PHP にて Zend_Validate_Callback とともに 使用される別の形式の次のようなクロージャを考えましょう。 例として:

$valid = new Zend_Validate_Callback(function($value){
    // some validation
    return true;
});

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

クラスに基づくコールバックの使用方法

もちろんクラスメソッドをコールバックとして使用することは可能です。 次のクラスメソッド を持ったつもりになりましょう:

class MyClass
{
    public function myMethod($value)
    {
        // いくつかのバリデーション
        return true;
    }
}

コールバックの定義はこのケースとほぼ同様です。メソッドより前にクラスインスタンス化して おいて、コールバックを取得する配列を生成します:

$object = new MyClass;
$valid = new Zend_Validate_Callback(array($object, 'myMethod'));
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

スタティックメソッドをコールバックとして定義することが可能です。 次のクラス定義を 考慮し、バリデータの使用方法は:

class MyClass
{
    public static function test($value)
    {
        // some validation
        return true;
    }
}

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

最終的に、あなたが PHP 5.3を使用しているならば、あなたのクラスにおいて __invoke() マジックメソッドを定義できます。 もしそうしたならば、 コールバックとして機能するクラスをインスタンス化したものを単に用意します。

class MyClass
{
    public function __invoke($value)
    {
        // some validation
        return true;
    }
}

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

オプションの追加

Zend_Validate_Callback は コールバックへ追加引数として提供されるオプションの使用を許容します。

次のクラスとメソッド定義を考えてみましょう:

class MyClass
{
    function myMethod($value, $option)
    {
        // some validation
        return true;
    }
}

バリデータに追加引数として通知する2つの方法があります: 追加引数をコンストラクタに渡すか setOptions() メソッドへ渡します。

コンストラクタに渡すには、"callback" と "options" を二つのキーにもつ配列を 渡す必要があります:

$valid = new Zend_Validate_Callback(array(
    'callback' => array('MyClass', 'myMethod'),
    'options'  => $option,
));

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

一方で、インスタンス化した後のバリデータへ渡せます:

$valid = new Zend_Validate_Callback(array('MyClass', 'myMethod'));
$valid->setOptions($option);

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

追加引数が isValid() へ渡されたとき、これらの 値は $value のすぐあとに追加されるでしょう。

$valid = new Zend_Validate_Callback(array('MyClass', 'myMethod'));
$valid->setOptions($option);

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

コールバックを呼び出す際には、 isValid() に渡される他の値全てを後ろに従えたコールバックに バリデートされる値が第一引数として常に渡されます。 他のオプションは全てその後に続きます。使用できるオプションの量と型は無制限です。

CreditCard

Zend_Validate_CreditCard allows you to validate if a given value could be a credit card number.

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

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

The following issuing institutes are accepted:

  • American Express

    China UnionPay

    Diners Club Card Blanche

    Diners Club International

    Diners Club US & Canada

    Discover Card

    JCB

    Laser

    Maestro

    MasterCard

    Solo

    Visa

    Visa Electron

Invalid institutes

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

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

Supported options for Zend_Validate_CreditCard

The following options are supported for Zend_Validate_CreditCard:

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

  • type: The type of creditcard which will be validated. See the below list of institutes for details.

Basic usage

There are several credit card institutes which can be validated by Zend_Validate_CreditCard. Per default, all known institutes will be accepted. See the folowing example:

$valid = new Zend_Validate_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_Validate_CreditCard allows you to do exactly this by limiting it to exactly these institutes.

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

You can provide a single institute:

$valid = new Zend_Validate_CreditCard(
    Zend_Validate_CreditCard::AMERICAN_EXPRESS
);

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

$valid = new Zend_Validate_CreditCard(array(
    Zend_Validate_CreditCard::AMERICAN_EXPRESS,
    Zend_Validate_CreditCard::VISA
));

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

$valid = new Zend_Validate_CreditCard(array(
    'type' => array(Zend_Validate_CreditCard::AMERICAN_EXPRESS)
));

表170 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().

$valid = new Zend_Validate_CreditCard();
$valid->setType(array(
    Zend_Validate_CreditCard::AMERICAN_EXPRESS,
    Zend_Validate_CreditCard::VISA
));

Default institute

When no institute is given at initiation then ALL will be used, which sets all institutes at once.

In this case the usage of addType() is useless because all institutes are already added.

Validation by using foreign APIs

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

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

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

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

// Your service class
class CcService
{
    public function checkOnline($cardnumber, $types)
    {
        // some online validation
    }
}

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

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

Ccnum

注記

Ccnum バリデータは、 CreditCard バリデータのほうを選んで非推奨になりました。 セキュリティ上の理由で、 Ccnum の代わりに CreditCard を使わなければなりません。

Date

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

Supported options for Zend_Validate_Date

The following options are supported for Zend_Validate_Date:

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

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

Default date validation

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

$validator = new Zend_Validate_Date();

$validator->isValid('2000-10-10');   // returns true
$validator->isValid('10.10.2000'); // returns false

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

Localized date validation

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

$validator = new Zend_Validate_Date(array('locale' => 'de'));

$validator->isValid('10.Feb.2010'); // returns true
$validator->isValid('10.May.2010'); // returns false

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

Self defined date validation

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

$validator = new Zend_Validate_Date(array('format' => 'yyyy'));

$validator->isValid('2010'); // returns true
$validator->isValid('May');  // returns false

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

$validator = new Zend_Validate_Date(array('format' => 'yyyy MMMM', 'locale' => 'de'));

$validator->isValid('2010 Dezember'); // returns true
$validator->isValid('2010 June');     // returns false

Db_RecordExists および Db_NoRecordExists

Zend_Validate_Db_RecordExists および Zend_Validate_Db_NoRecordExists は、 データベースのテーブル上に 指定した値のレコードが存在するかどうかを調べる手段を提供します。

Zend_Validate_Db_* でサポートされるオプション

Zend_Validate_Db_NoRecordExists および Zend_Validate_Db_RecordExists では下記のオプションがサポートされます。

  • adapter: 検索で使うデータベース・アダプタ

  • exclude: 検索から除外するレコードを設定します

  • field: レコードに対して検索される、このテーブル内のデータベース項目

  • schema: 検索で使うスキーマを設定します

  • table: レコードに対して検索されるテーブル

基本的な使用法

このバリデータの基本的な使用例です。

// メールアドレスがデータベース内に存在するかどうかを調べます
$validator = new Zend_Validate_Db_RecordExists(
    array(
        'table' => 'users',
        'field' => 'emailaddress'
    )
);
if ($validator->isValid($emailaddress)) {
    // メールアドレスは有効なようです
} else {
    // メールアドレスが無効なので、その理由を表示します
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

上の例は、指定したメールアドレスがデータベースのテーブル内に存在するかどうかを調べます。 指定したカラムの値が $emailaddress に一致するレコードがなければ、 エラーメッセージが表示されます。

// ユーザ名がデータベースに存在しないことを調べます
$validator = new Zend_Validate_Db_NoRecordExists(
    array(
        'table' => 'users',
        'field' => 'username'
    )
);
if ($validator->isValid($username)) {
    // ユーザ名は有効なようです
} else {
    // ユーザ名が無効なので、その理由を表示します
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}

上の例は、指定したユーザ名がデータベースのテーブル上に存在しないことを確認します。 指定したカラムの値が $username に一致するレコードが見つかれば、 エラーメッセージが表示されます。

レコードの除外

Zend_Validate_Db_RecordExists および Zend_Validate_Db_NoRecordExists には、 テーブルの一部を除外してその内容を調べる方法があります。 where 句を文字列で指定するか、あるいはキー "field" および "value" を含む配列を指定します。

除外条件を配列で指定すると、!= 演算子を使用します。 つまり、テーブル内の残りのレコードの内容を確認してからレコードを変更できるのです (たとえばユーザ情報のフォームなどで使用します)。

// そのユーザ名のユーザがほかにいないことを調べます
$user_id   = $user->getId();
$validator = new Zend_Validate_Db_NoRecordExists(
    array(
        'table' => 'users',
        'field' => 'username',
        'exclude' => array(
            'field' => 'id',
            'value' => $user_id
        )
    )
);

if ($validator->isValid($username)) {
    // ユーザ名は有効なようです
} else {
    // ユーザ名が無効なので、その理由を表示します
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}

上の例は、id = $user_id であるレコードを除いてそのテーブル内に $username を含むレコードが存在しないことを調べます。

除外条件を文字列で指定することもできるので、 != 以外の演算子を指定することもできます。 これは、複合キーに対するチェックの際に便利です。

$email     = 'user@example.com';
$clause    = $db->quoteInto('email = ?', $email);
$validator = new Zend_Validate_Db_RecordExists(
    array(
        'table'   => 'users',
        'field'   => 'username',
        'exclude' => $clause
    )
);

if ($validator->isValid($username)) {
    // ユーザ名は有効なようです
} else {
    // ユーザ名が無効なので、その理由を表示します
    $messages = $validator->getMessages();
    foreach ($messages as $message) {
        echo "$message\n";
    }
}

上の例では、ユーザ名 $username と email $email の両方を持つレコードだけが正しいことを確認するために、'users' テーブルを調べます。

データベースアダプタ

アダプタを指定することもできます。 複数のデータベースアダプタを使用している場合や デフォルトのアダプタを設定していない場合などにこれを使用します。 以下に例を示します。

$validator = new Zend_Validate_Db_RecordExists(
    array(
        'table' => 'users',
        'field' => 'id',
        'adapter' => $dbAdapter
    )
);

データベーススキーマ

データベース内のスキーマを PostgreSQL や DB/2 のアダプタで指定するには、キー table および schema を持つ配列を次の例のように渡します。 below:

$validator = new Zend_Validate_Db_RecordExists(
    array(
        'table'  => 'users',
        'schema' => 'my',
        'field'  => 'id'
    )
);

数字

Zend_Validate_Digits は、与えられた値が数字だけを含むかどうか検証します。

Zend_Validate_Digits でサポートされるオプション

Zend_Validate_Digits に対する追加オプションはありません。

数字を検証

任意の値が数字だけを含み、他の文字を含まないかどうか検証するには、 この例で示すようにバリデータを単純に呼び出します。

$validator = new Zend_Validate_Digits();

$validator->isValid("1234567890"); // true を返します
$validator->isValid(1234);         // true を返します
$validator->isValid('1a234');      // false を返します

数値を検証

数または数値を検証したい場合、このバリデータは、 数字だけを検証することに注意してください。 これは、千単位の分離記号またはコンマのような他の記号も一切 このバリデータを通過しないことを意味します。この場合には、 Zend_Validate_Int または Zend_Validate_Float を使用すべきです。

メールアドレス

Zend_Validate_EmailAddress は、メールアドレスの検証を行います。 このバリデータは、まずメールアドレスを local-part @ hostname に分割し、メールアドレスやホスト名の仕様にあわせて検証します。

基本的な使用法

基本的な使用法は、以下のようになります。

$validator = new Zend_Validate_EmailAddress();
if ($validator->isValid($email)) {
    // メールアドレスは正しい形式のようです
} else {
    // 不正な形式なので、理由を表示します
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

これは、メールアドレス $email を検証し、失敗した場合は その原因を表す便利なエラーメッセージを getMessages() で取得します。

メールアドレス検証のオプション

Zend_Validate_EmailAddressは、 開始時に関係するオプションを持つ配列を与えることによって、 または後で setOptions() を使って セットできるいくつかのオプションをサポートします。 下記のオプションがサポートされます。

  • allow: ドメイン名のいずれのタイプを受付可能か定義します。 このオプションは、ホスト名バリデータをセットするために hostname オプションとともに使われます。 このオプションで可能な値について詳しくは、 ホスト名をご覧ください。 そして ALLOW* 定数が可能です。 既定値は ALLOW_DNS です。

  • deep: サーバの MX レコードを強度のチェックで検証するべきかどうか定義します。 このオプションが TRUE に設定されると、 サーバがメールを受け付けるかどうか検証するために、 MX レコードに加えて A , A6 及び AAAA レコードも使われます。 このオプションの既定値は FALSE です。

  • domain: ドメインパートをチェックすべきかどうか定義します。 このオプションが FALSE に設定されると、 メールアドレスのローカルパートのみがチェックされます。 この場合、ホスト名バリデータは呼ばれません。 このオプションの既定値は TRUE です。

  • hostname: 検証される電子メール・アドレスのドメインパートで ホスト名バリデータをセットします。

  • mx: サーバから MX レコードが検出されるべきかどうか定義します。 もしこのオプションが TRUE と定義されると、 サーバがメールを受け付けるかどうか検証するために MX レコードが使われます。 このオプションの既定値は FALSE です。

$validator = new Zend_Validate_EmailAddress();
$validator->setOptions(array('domain' => false));

複雑なローカルパート

Zend_Validate_EmailAddress は、メールアドレスの検証を RFC2822 にもとづいて行います。たとえば、妥当な形式のメールアドレスとしては bob@domain.combob+jones@domain.us"bob@jones"@domain.com および "bob jones"@domain.com などがあります。

かつて使われていたものの、現在は有効とはみなされないフォーマットもあります (たとえば、メールアドレスに改行文字や "\" を使用するなど)。

ローカルパートのみの検証

もしメールアドレスのローカルパートのみをチェックするために Zend_Validate_EmailAddress を必要として、 ホスト名の検証を無効にしたいなら、 domain オプションに FALSE を設定できます。 これにより、 Zend_Validate_EmailAddress が メールアドレスのホスト名部分を検証しないようにします。

$validator = new Zend_Validate_EmailAddress();
$validator->setOptions(array('domain' => FALSE));

さまざまな形式のホスト名の検証

メールアドレスのホスト名部分の検証は、 Zend_Validate_Hostname で行います。デフォルトでは、domain.com 形式の DNS ホスト名のみが有効となります。しかし、 IP アドレスやローカルホスト名も有効にしたいこともあるでしょう。

その場合は、Zend_Validate_EmailAddress のインスタンスを作成する際にパラメータを渡さなければなりません。 このパラメータで、認めたいホスト名の形式を指定します。 詳細は Zend_Validate_Hostname を参照ください。 たとえば DNS ホスト名およびローカルホスト名のどちらも許可するには、次のようにします。

$validator = new Zend_Validate_EmailAddress(
                    Zend_Validate_Hostname::ALLOW_DNS |
                    Zend_Validate_Hostname::ALLOW_LOCAL);
if ($validator->isValid($email)) {
    // メールアドレスは正しい形式のようです
} else {
    // 不正な形式なので、理由を表示します
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

そのホスト名が実際にメールを受け付けるかどうかのチェック

ただ単にメールアドレスが正しい書式であるというだけでは、 そのアドレスが実際に存在するかどうかはわかりません。 この問題を解決するには、MX の検証を行います。 メールアドレスのホスト名に対応する DNS レコードに、MX (メール) のエントリが存在するかどうかを調べるのです。 これは、そのホストがメールを受け付けているかどうかを教えてはくれますが、 そのメールアドレス自体が正しいものであるかどうかを知ることはできません。

MX のチェックはデフォルトでは無効です。 MX のチェックを有効にするには、Zend_Validate_EmailAddress コンストラクタの 2 番目のパラメータを渡します。

$validator = new Zend_Validate_EmailAddress(
    array(
        'allow' => Zend_Validate_Hostname::ALLOW_DNS,
        'mx'    => true
    )
);

WindowsでのMX のチェック

Windows 環境の範囲内では、 MX のチェックは PHP 5.3 かそれ以上を使う場合のみ可能です。 PHP 5.3 未満では MX のチェックはオプションで有効にされたとしても、 使われません。

あるいは、TRUE または FALSEsetValidateMx() に渡すことで、 MX の検証を有効あるいは無効にすることもできます。

この設定を有効にすると、ネットワーク関数を用いて メールアドレスのホスト名部に対する MX レコードの存在チェックをします。 これにより、スクリプトの処理速度が低下することに気をつけてください。

しばしば MX レコードの検証は、メールが受け付けられたとしても FALSE を返します。 この振る舞いの背後にある理由は、サーバが MX レコードを提供しなくてもサーバはメールを受付できることです。 この場合、サーバは A, A6 または AAAA レコードを提供します。 それらのほかのレコードでも Zend_Validate_EmailAddress がチェックできるようにするためには、 強度の MX 検証を設定する必要があります。 これは開始時に deep オプションを設定するか、 または setOptions() を使って行ないます。

$validator = new Zend_Validate_EmailAddress(
    array(
        'allow' => Zend_Validate_Hostname::ALLOW_DNS,
        'mx'    => true,
        'deep'  => true
    )
);

パフォーマンスの警告

MX チェックを有効にすると、使用されるネットワーク機能のせいで スクリプトが遅くなることに気づくでしょう。 強度のチェックを有効にすると与えられたサーバで追加の3種類を探すため、 さらにスクリプトが遅くなります。

許可されないIPアドレス

MX 検証は外部のサーバでのみ受け付けられることを注意すべきです。 強度の MX 検証が有効なとき、 192.168.*169.254.* のような ローカル IP アドレスは受け付けません。

国際化ドメイン名の検証

Zend_Validate_EmailAddress は、ドメインの中に国際文字が使われている場合も処理できます。 このようなドメインは、国際化ドメイン名 (International Domain Name: IDN) と呼ばれています。これはデフォルトで有効になっていますが、無効にすることも可能です。 無効にするには、Zend_Validate_EmailAddress が内部で保持している Zend_Validate_Hostname オブジェクトの設定を変更します。

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

setValidateIdn() の詳細な使用法は、 Zend_Validate_Hostname のドキュメントを参照ください。

IDN の検証は、DNS ホスト名の検証を有効にしている場合にのみ行われることに注意しましょう。

トップレベルドメインの検証

デフォルトでは、ホスト名の検証は既知の TLD の一覧に基づいて行われます。 これはデフォルトで有効になっていますが、無効にすることもできます。無効にするには、 無効にするには、Zend_Validate_EmailAddress が内部で保持している Zend_Validate_Hostname オブジェクトの設定を変更します。

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

setValidateTld() の詳細な使用法は、 Zend_Validate_Hostname のドキュメントを参照ください。

TLD の検証は、DNS ホスト名の検証を有効にしている場合にのみ行われることに注意しましょう。

メッセージの設定

Zend_Validate_EmailAddress は、 Zend_Validate_Hostname を使用してメールアドレスのホスト名部分をチェックします。 Zend Framework 1.10 以降、 Zend_Validate_Hostname 用のメッセージを Zend_Validate_EmailAddress から設定できるようになります。

$validator = new Zend_Validate_EmailAddress();
$validator->setMessages(
    array(
        Zend_Validate_Hostname::UNKNOWN_TLD => "I don't know the TLD you gave"
    )
);

Zend Framework 1.10 より前のバージョンでは、まず Zend_Validate_Hostname にメッセージをアタッチしてからそれを Zend_Validate_EmailAddress に設定しないと独自のメッセージを返せませんでした。

Float

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

Supported options for Zend_Validate_Float

The following options are supported for Zend_Validate_Float:

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

Simple float validation

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

$validator = new Zend_Validate_Float();

$validator->isValid(1234.5);   // returns true
$validator->isValid('10a01'); // returns false
$validator->isValid('1,234.5'); // returns true

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

Localized float validation

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

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

$validator = new Zend_Validate_Float(array('locale' => 'de'));

$validator->isValid(1234.5); // returns true
$validator->isValid("1 234,5"); // returns false
$validator->isValid("1.234"); // returns true

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

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

GreaterThan(日本語)

Zend_Validate_GreaterThan により、 与えられた値が最小の境界値よりも大きいかどうか検証できます。

Zend_Validate_GreaterThan は、数値の検証のみサポートします

Zend_Validate_GreaterThan は、 数値の検証のみをサポートすることに注意してください。 文字列や日付はこのバリデータでは検証できません。

Zend_Validate_GreaterThan でサポートされるオプション

Zend_Validate_GreaterThan では、下記のオプションがサポートされます。

  • min: 許される最小値を設定します。

基本的な使用法

任意の値が定義済みの境界より大きいかどうか検証するには、 単に以下の例を使います。

$valid  = new Zend_Validate_GreaterThan(array('min' => 10));
$value  = 10;
$return = $valid->isValid($value);
// true を返します。

上記の例は、10 以上の全ての値で TRUE を返します。

Hex(日本語)

Zend_Validate_Hex により、 任意の値が16進の文字だけを含むかどうか検証できます。 それらは、0 から 9 までと、 文字の大小を区別しないA から F までの、全ての文字です。 検証したい入力に対する長さの制限はありません。

$validator = new Zend_Validate_Hex();
if ($validator->isValid('123ABC')) {
    // value contains only hex chars
} else {
    // false
}

無効な文字

他の文字は全て false を返します。それには空白や小数点を含みます。 ラテン文字以外の文書由来のユニコードのゼロや数字も、無効として扱われます。

Zend_Validate_Hex でサポートされるオプション

Zend_Validate_Hex に対する追加オプションはありません。

ホスト名

Zend_Validate_Hostname は、ホスト名が仕様を満たしているかどうかの検証を行います。 三種類の形式のホスト名、つまり DNS ホスト名 (たとえば domain.com)、IP アドレス (たとえば 1.2.3.4) そしてローカルホスト名 (たとえば localhost) の検証が可能です。 デフォルトでは DNS ホスト名のみが有効となります。

Zend_Validate_Hostname でサポートされるオプション

Zend_Validate_Hostname では、下記のオプションがサポートされます。

  • allow: 使用できるホスト名のソートを定義します。 詳しくは、ホスト名の種類 をご覧ください。

  • idn: IDN ドメインが許可されるかどうか定義します。 このオプションのデフォルトは TRUE です。

  • ip: これにより、固有の IP バリデーターを定義できます。 このオプションのデフォルトは Zend_Validate_Ip の新規インスタンスです。

  • tld: TLD が検証されるかどうか定義します。 このオプションのデフォルトは TRUE です。

基本的な使用法

基本的な使用法は、以下のようになります。

$validator = new Zend_Validate_Hostname();
if ($validator->isValid($hostname)) {
    // ホスト名は正しい形式のようです
} else {
    // 不正な形式なので、理由を表示します
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

これは、ホスト名 $hostname を検証し、失敗した場合は その原因を表す便利なエラーメッセージを $validator->getMessages() で取得します。

さまざまな形式のホスト名を検証

IP アドレスやローカルホスト名、あるいはその両方を正しいホスト名として認めたいこともあるでしょう。 その場合は、Zend_Validate_Hostname のインスタンスを作成する際にパラメータを渡します。 このパラメータには、どの形式のホスト名を許可するのかを表す整数値を指定しなければなりません。 できるだけ、Zend_Validate_Hostname の定数を使用するようにしましょう。

Zend_Validate_Hostname の定数は次のとおりです。 ALLOW_DNSDNS ホスト名のみ、 ALLOW_IP は IP アドレス、 ALLOW_LOCAL はローカルネットワーク名、 ALLOW_URIRFC3986 に準拠するアドレス、 ALLOW_ALL は前述の4種類のすべて、 を許可します。

ALLOW_URI に関する追加情報

ALLOW_URI により、RFC3986 に従うホスト名をチェックできます。 これらは、WINS、NetInfo、および .hosts ファイル内で定義されるそれらのようなローカル・ホスト名によって使用される登録された名前です。

IP アドレスだけをチェックするには、以下の例のようにします。

$validator = new Zend_Validate_Hostname(Zend_Validate_Hostname::ALLOW_IP);
if ($validator->isValid($hostname)) {
    // ホスト名は正しい形式のようです
} else {
    // 不正な形式なので、理由を表示します
    foreach ($validator->getMessages() as $message) {
        echo "$message\n";
    }
}

ALLOW_ALL を使用して共通のすべてのホスト名形式を許可するほかに、 これらの形式を組み合わせることもできます。 たとえば、 DNS およびローカルホスト名を許可するには、 Zend_Validate_Hostname のインスタンスを次のように作成します。

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

国際化ドメイン名を検証

国別コードトップレベルドメイン (Country Code Top Level Domains: ccTLDs) の一部、たとえば 'de' (ドイツ) などでは、ドメイン名の中に国際化文字の使用をサポートしています。 これは、国際化ドメイン名 (International Domain Names: IDN) といわれるものです。 これらのドメインについても、Zend_Validate_Hostname の検証プロセスで使用する文字を拡張することで検証できます。

IDN ドメイン

これまでに、50以上の ccTLD が IDN ドメインをサポートします。

IDN ドメインに対するマッチングを行う方法は、通常のホスト名の場合とまったく同じです。 というのも、 IDN のマッチングはデフォルトで有効になっているからです。 IDN の検証を無効にしたい場合は、Zend_Validate_Hostname のコンストラクタにパラメータを渡すか、あるいは setValidateIdn() メソッドを使用します。

IDN の検証を無効にするには、Zend_Validate_Hostname のコンストラクタに二番目のパラメータを次のように渡します。

$validator =
    new Zend_Validate_Hostname(
        array(
            'allow' => Zend_Validate_Hostname::ALLOW_DNS,
            'idn'   => false
        )
    );

あるいは、 TRUE または FALSEsetValidateIdn() に渡すことで、 IDN の検証を有効あるいは無効にすることもできます。 現在サポートされていない IDN ホスト名に対するマッチングを行おうとすると、 国際化文字が含まれている場合に検証に失敗します。 追加の文字を指定した ccTLD ファイルが Zend/Validate/Hostname に存在しない場合は、通常のホスト名の検証を行います。

IDN 検証

IDN の検証は、 DNS ホスト名の検証を有効にしている場合にのみ行われることに注意しましょう。

トップレベルドメインを検証

デフォルトでは、ホスト名の検証は既知の TLD の一覧に基づいて行われます。 この機能が不要な場合は、 IDN サポートを無効にするのと同じ方法で無効にできます。 TLD の検証を無効にするには、Zend_Validate_Hostname のコンストラクタに三番目のパラメータを渡します。 以下の例では、 IDN の検証は二番目のパラメータで有効にしています。

$validator =
    new Zend_Validate_Hostname(
        array(
            'allow' => Zend_Validate_Hostname::ALLOW_DNS,
            'idn'   => true,
            'tld'   => false
        )
    );

あるいは、 TRUE または FALSEsetValidateIdn() に渡すことで、 TLD の検証を有効あるいは無効にすることもできます。

TLD 検証

TLD の検証は、 DNS ホスト名の検証を有効にしている場合にのみ行われることに注意しましょう。

Iban

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

Supported options for Zend_Validate_Iban

The following options are supported for Zend_Validate_Iban:

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

IBAN validation

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

Application wide locale

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

// within bootstrap
Zend_Registry::set('Zend_Locale', new Zend_Locale('de_AT'));

// within the module
$validator = new Zend_Validate_Iban();

if ($validator->isValid('AT611904300234573201')) {
    // IBAN appears to be valid
} else {
    // IBAN is not valid
}

Application wide locale

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

Ungreedy IBAN validation

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

$validator = new Zend_Validate_Iban(array('locale' => false));
// Note: you can also set a FALSE as single parameter

if ($validator->isValid('AT611904300234573201')) {
    // IBAN appears to be valid
} else {
    // IBAN is not valid
}

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

Region aware IBAN validation

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

$validator = new Zend_Validate_Iban(array('locale' => 'de_AT'));

if ($validator->isValid('AT611904300234573201')) {
    // IBAN appears to be valid
} else {
    // IBAN is not valid
}

Use full qualified locales

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

Identical

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

Supported options for Zend_Validate_Identical

The following options are supported for Zend_Validate_Identical:

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

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

Basic usage

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

$valid = new Zend_Validate_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_Validate_Identical can not only validate strings, but also any other variable type like Boolean, Integer, Float, Array or even Objects. As already noted Haystack and Value must be identical.

$valid = new Zend_Validate_Identical(123);
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

Type comparison

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

Form elements

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

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

$valid = new Zend_Validate_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 convinience you can also use setStrict() and getStrict().

Configuration

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

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

$valid = new Zend_Validate_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.

$valid = new Zend_Validate_Identical(array('token' => array('token' => 123)));
if ($valid->isValid($input)) {
    // input appears to be valid
} else {
    // input is invalid
}

InArray(日本語)

任意の値が配列の中で含まれるかどうか、 Zend_Validate_InArrayで検証できます。 それは、多次元配列を確認することもできます。

Zend_Validate_InArray でサポートされるオプション

下記のオプションが Zend_Validate_InArray でサポートされます。

  • haystack: 検証に対するヘイスタックを設定します。

  • recursive: 検証が再帰的に行なわれるべきかどうか定義します。 このオプションの既定値は FALSE です。

  • strict: 検証が厳密に行なわれるべきかどうか定義します。 このオプションの既定値は FALSE です。

単純な配列の検証

最も単純な方法は、初期化の際に検索される配列を与えることがまさにそうです。

$validator = new Zend_Validate_InArray(array('key' => 'value',
                                             'otherkey' => 'othervalue'));
if ($validator->isValid('value')) {
    // 値が見つかりました
} else {
    // 値が見つかりません
}

これは、ちょうどPHPin_array() メソッドのようにふるまいます

注記

デフォルトでは、この検証は厳格ではありませんし、 それは多次元配列を検証することができません。

もちろん、setHaystack()メソッドを用いてその後また、 検証する配列を与えることができます。 getHaystack() は、実際に設定されている配列を返します。

$validator = new Zend_Validate_InArray();
$validator->setHaystack(array('key' => 'value', 'otherkey' => 'othervalue'));

if ($validator->isValid('value')) {
    // 値が見つかりました
} else {
    // 値が見つかりません
}

厳密な配列の検証

上述のように、配列の中で厳密な検証をすることもできます。 デフォルトでは、整数値0と文字列"0"の違いがありません。 厳密な検証をするときは、この違いも検証されます。そして、同じ型だけが受け入れられます。

厳密な検証は、異なる2つの方法を用いて行なうこともできます。 初期化で、及びメソッドを用いて。 初期化では、以下の構造で配列を与えなければなりません。

$validator = new Zend_Validate_InArray(
    array(
        'haystack' => array('key' => 'value', 'otherkey' => 'othervalue'),
        'strict'   => true
    )
);

if ($validator->isValid('value')) {
    // 値が見つかりました
} else {
    // 値が見つかりません
}

haystackキーは、検証する配列を含みます。 そしてstrictキーをTRUEに設定することにより、 検証は厳密な型チェックを用いてなされます。

もちろん、その後この設定値を変えるために、 setStrict()メソッドを使うこともできます。 また、getStrict() で実際に設定されている内容を取得することもできます。

注記

strict設定は、 デフォルトではFALSEであることに注意してください。

再帰的な配列の検証

PHPin_array()メソッド に加えて、このバリデータは、多次元配列を検証するために使うこともできます。

多次元配列を検証するためには、 recursiveオプションを設定しなければなりません。

$validator = new Zend_Validate_InArray(
    array(
        'haystack' => array(
            'firstDimension' => array('key' => 'value',
                                      'otherkey' => 'othervalue'),
            'secondDimension' => array('some' => 'real',
                                       'different' => 'key')),
        'recursive' => true
    )
);

if ($validator->isValid('value')) {
    // 値が見つかりました
} else {
    // 値が見つかりません
}

それにより、任意の値が含まれるかどうか配列が再帰的に検証されます。 さらに、setRecursive() を使って後からこのオプションを設定したり getRecursive() で設定を取得したりすることもできます。

$validator = new Zend_Validate_InArray(
    array(
        'firstDimension' => array('key' => 'value',
                                  'otherkey' => 'othervalue'),
        'secondDimension' => array('some' => 'real',
                                   'different' => 'key')
    )
);
$validator->setRecursive(true);

if ($validator->isValid('value')) {
    // 値が見つかりました
} else {
    // 値が見つかりません
}

再帰的な検証のデフォルト設定

デフォルトでは再帰的な検証は無効となります。

配列内でのオプションキー

'haystack' や 'strict'、'recursive' といったキーを配列内で使う場合は、haystack キーをラップしなければなりません。

Int

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

Supported options for Zend_Validate_Int

The following options are supported for Zend_Validate_Int:

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

Simple integer validation

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

$validator = new Zend_Validate_Int();

$validator->isValid(1234);   // returns true
$validator->isValid(1234.5); // returns false
$validator->isValid('1,234'); // returns true

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

Localized integer validation

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

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

$validator = new Zend_Validate_Int(array('locale' => 'de'));

$validator->isValid(1234); // returns true
$validator->isValid("1,234"); // returns false
$validator->isValid("1.234"); // returns true

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

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

Ip(日本語)

Zend_Validate_Ip は、与えられた値が IP アドレスかどうか検証できるようにします。 これは IPv4 及び IPv6 標準をサポートします。

Zend_Validate_Ip でサポートされるオプション

Zend_Validate_Ip では、下記のオプションがサポートされます。

  • allowipv4: バリデータが IPv4 アドレスを許すかどうかを定義します。 このオプションのデフォルトは TRUE です。

  • allowipv6: バリデータが IPv6 アドレスを許すかどうかを定義します。 このオプションのデフォルトは TRUE です。

基本的な使用法

基本的な使用法は、以下のようになります。

$validator = new Zend_Validate_Ip();
if ($validator->isValid($ip)) {
    // ip は正しい形式のようです
} else {
    // ip が不正なので、理由を表示します
}

IP アドレスの検証

Zend_Validate_Ip は IP アドレスだけを検証することを記憶にとどめてください。 'mydomain.com' や '192.168.50.1/index.html' のようなアドレスは、有効な IP アドレスではありません。 それらは IP アドレスではなく、 hostname または 有効な URL です。

IPv6 の検証

Zend_Validate_Ip は正規表現で IPv6 アドレスを検証します。 それは、 PHP 自身のフィルターやメソッドが RFC に準拠していないからです。 他の多くの利用可能なクラスもまた、それに準拠しません。

IPv4 または IPV6 だけを検証

しばしば、サポートされる形式のうちの1つだけを検証するために役立ちます。 たとえば、ネットワークが IPv4 だけをサポートするときです。 この場合、このバリデータ内で IPv6 を受け付けることは無駄でしょう。

Zend_Validate_Ip をプロトコル1つに制限するために、 オプション allowipv4 または allowipv6FALSE に設定できます。 これは、コンストラクタにオプションを与えることによって、 または、その後 setOptions() を用いて行なえます。

$validator = new Zend_Validate_Ip(array('allowipv6' => false);
if ($validator->isValid($ip)) {
    // ip は正しい ip4v アドレスのようです
} else {
    // ip は ipv4 アドレスではありません
}

既定の動作

Zend_Validate_Ip が従う既定の動作は 両方の標準を受け付ける、です。

Isbn

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

Supported options for Zend_Validate_Isbn

The following options are supported for Zend_Validate_Isbn:

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

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

Basic usage

A basic example of usage is below:

$validator = new Zend_Validate_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:

$validator = new Zend_Validate_Isbn();
$validator->setType(Zend_Validate_Isbn::ISBN13);
// OR
$validator = new Zend_Validate_Isbn(array(
    'type' => Zend_Validate_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_Validate_Isbn::AUTO (default)

  • Zend_Validate_Isbn::ISBN10

  • Zend_Validate_Isbn::ISBN13

Specifying a separator restriction

An example of separator restriction is below:

$validator = new Zend_Validate_Isbn();
$validator->setSeparator('-');
// OR
$validator = new Zend_Validate_Isbn(array(
    'separator' => '-',
));

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

Values without separator

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

Valid separators include:

  • "" (empty) (default)

  • "-" (hyphen)

  • " " (space)

LessThan(日本語)

Zend_Validate_LessThan により、 与えられた値が最大の境界値よりも小さいかどうか検証できます。 それは Zend_Validate_GreaterThan に対応するものです。

Zend_Validate_LessThan は、数値の検証のみサポートします

Zend_Validate_LessThan は、 数値の検証のみをサポートすることに注意してください。 文字列や日付はこのバリデータでは検証できません。

Zend_Validate_LessThan でサポートされるオプション

Zend_Validate_LessThan では、下記のオプションがサポートされます。

  • max: 許される最大値を設定します。

基本的な使用法

任意の値が定義済みの境界より小さいかどうか検証するには、 単に以下の例を使います。

$valid  = new Zend_Validate_LessThan(array('max' => 10));
$value  = 10;
$return = $valid->isValid($value);
// true を返します。

上記の例は、10 以下の全ての値で TRUE を返します。

NotEmpty

This validator allows you to validate if a given value is not empty. This is often useful when working with form elements or other user input, where you can use it to ensure required elements have values associated with them.

Supported options for Zend_Validate_NotEmpty

The following options are supported for Zend_Validate_NotEmpty:

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

Default behaviour for Zend_Validate_NotEmpty

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

$valid = new Zend_Validate_NotEmpty();
$value  = '';
$result = $valid->isValid($value);
// returns false

Default behaviour differs from PHP

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

Changing behaviour for Zend_Validate_NotEmpty

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

The following types can be handled:

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

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

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

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

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

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

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

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

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

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

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

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

  • all: Returns FALSE on all above types.

All other given values will return TRUE per default.

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

// Returns false on 0
$validator = new Zend_Validate_NotEmpty(Zend_Validate_NotEmpty::INTEGER);

// Returns false on 0 or '0'
$validator = new Zend_Validate_NotEmpty(
    Zend_Validate_NotEmpty::INTEGER + Zend_NotEmpty::ZERO
);

// Returns false on 0 or '0'
$validator = new Zend_Validate_NotEmpty(array(
    Zend_Validate_NotEmpty::INTEGER,
    Zend_Validate_NotEmpty::ZERO
));

// Returns false on 0 or '0'
$validator = new Zend_Validate_NotEmpty(array(
    'integer',
    'zero',
));

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

PostCode

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

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

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

$validator = new Zend_Validate_PostCode('de_AT');

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

// application wide locale within your bootstrap
$locale = new Zend_Locale('de_AT');
Zend_Registry::set('Zend_Locale', $locale);

$validator = new Zend_Validate_PostCode();

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

$validator = new Zend_Validate_PostCode('de_AT');
$validator->setLocale('en_GB');

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

$validator = new Zend_Validate_PostCode('de_AT');
$validator->setFormat('AT-\d{5}');

Conventions for self defined formats

When using self defined formats you should omit the starting ('/^') and ending tags ('$/'). They are attached automatically.

You should also be aware that postcode values are always be validated in a strict way. This means that they have to be written standalone without additional characters when they are not covered by the format.

Constructor options

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

$validator = new Zend_Validate_PostCode('de_AT');
$validator = new Zend_Validate_PostCode($locale);

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

$validator = new Zend_Validate_PostCode(array(
    'locale' => 'de_AT',
    'format' => 'AT_\d+'
));

Supported options for Zend_Validate_PostCode

The following options are supported for Zend_Validate_PostCode:

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

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

Regex

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

Supported options for Zend_Validate_Regex

The following options are supported for Zend_Validate_Regex:

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

Validation with Zend_Validate_Regex

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

$validator = new Zend_Validate_Regex(array('pattern' => '/^Test/');

$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns true
$validator->isValid("Pest"); // returns false

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

Pattern handling

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

$validator = new Zend_Validate_Regex(array('pattern' => '/^Test/');
$validator->setPattern('ing$/');

$validator->isValid("Test"); // returns false
$validator->isValid("Testing"); // returns true
$validator->isValid("Pest"); // returns false

サイトマップ・バリデータ

以下のバリデータは、 サイトマップ XML プロトコル に従います。

Sitemap_Changefreq

文字列がサイトマップ XML 文書で 'changefreq' 要素として 使用できるかどうか検証します。 有効値は、 'always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly' または 'never' です。

値が文字列で、上記で指定される頻度のうちの1つと等しい場合に限り、 TRUEを返します。

Sitemap_Lastmod

文字列がサイトマップ XML 文書で 'lastmod' 要素として 使用できるかどうか検証します。 lastmod要素は W3C 日付文字列を含まなければなりません。 そして、任意で時間についての情報を無効にします。

値が文字列で、プロトコルに従って妥当な場合に限り、 TRUEを返します。

例941 サイトマップ Lastmod バリデータ

$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

文字列がサイトマップ XML 文書で 'loc' 要素として 使用できるかどうか検証します。 これは内部的にZend_Form::check()を使います。 詳しくはURI の検証を読んでください。

Sitemap_Priority

文字列がサイトマップ XML 文書で 'priority' 要素として 使用できるかどうか検証します。 値は、0.0と1.0の間の小数でなければなりません。 このバリデータは、数値と文字列値の両方を受け入れます。

例942 サイトマップ 優先度 バリデータ

$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

Zend_Validate_Sitemap_* でサポートされるオプション

サイトマップ・バリデータのいずれもサポートするオプションはありません。

StringLength

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

Zend_Validate_StringLength supports only string validation

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

Supported options for Zend_Validate_StringLength

The following options are supported for Zend_Validate_StringLength:

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

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

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

Default behaviour for Zend_Validate_StringLength

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

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

Limiting the maximum allowed length of a string

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

$validator = new Zend_Validate_StringLength(array('max' => 6));

$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns false

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

$validator = new Zend_Validate_StringLength();
$validator->setMax(6);

$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns false

Limiting the minimal required length of a string

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

$validator = new Zend_Validate_StringLength(array('min' => 5));

$validator->isValid("Test"); // returns false
$validator->isValid("Testing"); // returns true

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

$validator = new Zend_Validate_StringLength();
$validator->setMin(5);

$validator->isValid("Test"); // returns false
$validator->isValid("Testing"); // returns true

Limiting a string on both sides

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

$validator = new Zend_Validate_StringLength(array('min' => 3, 'max' => 30));

$validator->isValid("."); // returns false
$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns true

Setting a lower maximum border than the minimum border

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

Encoding of values

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

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

$validator = new Zend_Validate_StringLength(
    array('min' => 6)
);
$validator->isValid("Ärger"); // returns false

$validator->setEncoding("UTF-8");
$validator->isValid("Ärger"); // returns true

$validator2 = new Zend_Validate_StringLength(
    array('min' => 6, 'encoding' => 'UTF-8')
);
$validator2->isValid("Ärger"); // returns true

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