update v1.0.7.9 R.C.

This is a Release Candidate. We are still testing.
This commit is contained in:
Sujit Prasad
2016-08-03 20:04:36 +05:30
parent 8b6b924d09
commit ffa56a43cb
3830 changed files with 181529 additions and 495353 deletions

View File

@@ -0,0 +1,12 @@
<div class="container">
<div class="jumbotron">
<h1>zend-validator</h1>
<p>
Validation classes for a wide range of domains, and the ability to chain validators to create complex validation criteria.
</p>
<pre><code class="language-bash">$ composer require zendframework/zend-validator</code></pre>
</div>
</div>

View File

@@ -0,0 +1 @@
../../README.md

View File

@@ -0,0 +1,213 @@
# Introduction
zend-validator provides a set of commonly needed validators. It also provides a
simple validator chaining mechanism by which multiple validators may be applied
to a single datum in a user-defined order.
## What is a validator?
A validator examines its input with respect to some requirements and produces a
boolean result indicating whether the input successfully validates against the
requirements. If the input does not meet the requirements, a validator may
additionally provide information about which requirement(s) the input does not
meet.
For example, a web application might require that a username be between six and
twelve characters in length, and may only contain alphanumeric characters. A
validator can be used for ensuring that a username meets these requirements. If
a chosen username does not meet one or both of the requirements, it would be
useful to know which of the requirements the username fails to meet.
## Basic usage of validators
Having defined validation in this way provides the foundation for
`Zend\Validator\ValidatorInterface`, which defines two methods, `isValid()` and
`getMessages()`. The `isValid()` method performs validation upon the provided
value, returning `true` if and only if the value passes against the validation
criteria.
If `isValid()` returns `false`, the `getMessages()` method will return an array
of messages explaining the reason(s) for validation failure. The array keys are
short strings that identify the reasons for validation failure, and the array
values are the corresponding human-readable string messages. The keys and values
are class-dependent; each validation class defines its own set of validation
failure messages and the unique keys that identify them. Each class also has a
`const` definition that matches each identifier for a validation failure cause.
> ### Stateful validators
>
> The `getMessages()` methods return validation failure information only for the
> most recent `isValid()` call. Each call to `isValid()` clears any messages and
> errors caused by a previous `isValid()` call, because it's likely that each
> call to `isValid()` is made for a different input value.
The following example illustrates validation of an e-mail address:
```php
use Zend\Validator\EmailAddress;
$validator = new EmailAddress();
if ($validator->isValid($email)) {
// email appears to be valid
} else {
// email is invalid; print the reasons
foreach ($validator->getMessages() as $messageId => $message) {
printf("Validation failure '%s': %s\n", $messageId, $message);
}
}
```
## Customizing messages
Validator classes provide a `setMessage()` method with which you can specify the
format of a message returned by `getMessages()` in case of validation failure.
The first argument of this method is a string containing the error message. You
can include tokens in this string which will be substituted with data relevant
to the validator. The token `%value%` is supported by all validators; this is
substituted with the value you passed to `isValid()`. Other tokens may be
supported on a case-by-case basis in each validation class. For example, `%max%`
is a token supported by `Zend\Validator\LessThan`. The `getMessageVariables()`
method returns an array of variable tokens supported by the validator.
The second optional argument is a string that identifies the validation failure
message template to be set, which is useful when a validation class defines more
than one cause for failure. If you omit the second argument, `setMessage()`
assumes the message you specify should be used for the first message template
declared in the validation class. Many validation classes only have one error
message template defined, so there is no need to specify which message template
you are changing.
```php
use Zend\Validator\StringLength;
$validator = new StringLength(8);
$validator->setMessage(
'The string \'%value%\' is too short; it must be at least %min% characters',
StringLength::TOO_SHORT
);
if (! $validator->isValid('word')) {
$messages = $validator->getMessages();
echo current($messages);
// "The string 'word' is too short; it must be at least 8 characters"
}
```
You can set multiple messages using the `setMessages()` method. Its argument is
an array containing key/message pairs.
```php
use Zend\Validator\StringLength;
$validator = new StringLength(['min' => 8, 'max' => 12]);
$validator->setMessages([
StringLength::TOO_SHORT => 'The string \'%value%\' is too short',
StringLength::TOO_LONG => 'The string \'%value%\' is too long',
]);
```
If your application requires even greater flexibility with which it reports
validation failures, you can access properties by the same name as the message
tokens supported by a given validation class. The `value` property is always
available in a validator; it is the value you specified as the argument of
`isValid()`. Other properties may be supported on a case-by-case basis in each
validation class.
```php
use Zend\Validator\StringLength;
$validator = new StringLength(['min' => 8, 'max' => 12]);
if (! $validator->isValid('word')) {
printf(
"Word failed: %s; its length is not between %d and %d\n",
$validator->value,
$validator->min,
$validator->max
);
}
```
## Translating messages
> ### Translation compatibility
>
> In versions 2.0 - 2.1, `Zend\Validator\AbstractValidator` implemented
> `Zend\I18n\Translator\TranslatorAwareInterface` and accepted instances of
> `Zend\I18n\Translator\Translator`. Starting in version 2.2.0, zend-validator
> now defines a translator interface, > `Zend\Validator\Translator\TranslatorInterface`,
> as well as it's own -aware variant, > `Zend\Validator\Translator\TranslatorAwareInterface`.
> This was done to reduce dependencies for the component, and follows the
> principal of Separated Interfaces.
>
> The upshot is that if you are migrating from a pre-2.2 version, and receiving
> errors indicating that the translator provided does not implement
> `Zend\Validator\Translator\TranslatorInterface`, you will need to make a
> change to your code.
>
> An implementation of `Zend\Validator\Translator\TranslatorInterface` is
> provided in `Zend\Mvc\I18n\Translator`, which also extends
> `Zend\I18n\Translator\Translator`. This version can be instantiated and used
> just as the original `Zend\I18n` version.
>
> A new service has also been registered with the MVC, `MvcTranslator`, which
> will return this specialized, bridge instance.
>
> Most users should see no issues, as `Zend\Validator\ValidatorPluginManager`
> has been modified to use the `MvcTranslator` service internally, which is how
> most developers were getting the translator instance into validators in the
> first place. You will only need to change code if you were manually injecting
> the instance previously.
Validator classes provide a `setTranslator()` method with which you can specify
an instance of `Zend\Validator\Translator\TranslatorInterface` which will
translate the messages in case of a validation failure. The `getTranslator()`
method returns the translator instance. `Zend\Mvc\I18n\Translator` provides an
implementation compatible with the validator component.
```php
use Zend\Mvc\I18n\Translator;
use Zend\Validator\StringLength;
$validator = new StringLength(['min' => 8, 'max' => 12]);
$translate = new Translator();
// configure the translator...
$validator->setTranslator($translate);
```
With the static `AbstractValidator::setDefaultTranslator()` method you can set a
instance of `Zend\Validator\Translator\TranslatorInterface` which will be used
for all validation classes, and can be retrieved with `getDefaultTranslator()`.
This prevents the need for setting a translator manually with each validator.
```php
use Zend\Mvc\I18n\Translator;
use Zend\Validator\AbstractValidator;
$translate = new Translator();
// configure the translator...
AbstractValidator::setDefaultTranslator($translate);
```
Sometimes it is necessary to disable the translator within a validator. To
achieve this you can use the `setDisableTranslator()` method, which accepts a
boolean parameter, and `isTranslatorDisabled()` to get the set value.
```php
use Zend\Validator\StringLength;
$validator = new StringLength(['min' => 8, 'max' => 12]);
if (! $validator->isTranslatorDisabled()) {
$validator->setDisableTranslator();
}
```
It is also possible to use a translator instead of setting own messages with
`setMessage()`. But doing so, you should keep in mind, that the translator works
also on messages you set your own.

View File

@@ -0,0 +1,108 @@
# Validation Messages
Each validator based on `Zend\Validator\ValidatorInterface` provides one or
multiple messages in the case of a failed validation. You can use this
information to set your own messages, or to translate existing messages which a
validator could return to something different.
Validation messages are defined as constant/template pairs, with the constant
representing a translation key. Such constants are defined per-class. Let's
look into `Zend\Validator\GreaterThan` for a descriptive example:
```php
protected $messageTemplates = [
self::NOT_GREATER => "'%value%' is not greater than '%min%'",
];
```
The constant `self::NOT_GREATER` refers to the failure and is used as the
message key, and the message template itself is used as the value within the
message array.
You can retrieve all message templates from a validator by using the
`getMessageTemplates()` method. It returns the above array containing all
messages a validator could return in the case of a failed validation.
```php
$validator = new Zend\Validator\GreaterThan();
$messages = $validator->getMessageTemplates();
```
Using the `setMessage()` method you can set another message to be returned in
case of the specified failure.
```php
use Zend\Validator\GreaterThan;
$validator = new GreaterThan();
$validator->setMessage('Please enter a lower value', GreaterThan::NOT_GREATER);
```
The second parameter defines the failure which will be overridden. When you omit
this parameter, then the given message will be set for all possible failures of
this validator.
## Using pre-translated validation messages
zend-validator is shipped with more than 45 different validators with more than
200 failure messages. It can be a tedious task to translate all of these
messages. For your convenience, pre-translated messages are provided in the
[zendframework/zend-i18n-resources](https://zendframework.github.io/zend-i18n-resources/)
package:
```bash
$ composer require zendframework/zend-i18n-resources
```
To translate all validation messages to German for example, attach a translator
to `Zend\Validator\AbstractValidator` using these resource files.
```php
use Zend\I18n\Translator\Resources;
use Zend\Mvc\I18n\Translator;
use Zend\Validator\AbstractValidator;
$translator = new Zend\Mvc\I18n\Translator();
$translator->addTranslationFilePattern(
'phpArray',
Resources::getBasePath(),
Resources::getPatternForValidator()
);
AbstractValidator::setDefaultTranslator($translator);
```
> ### Supported languages
>
> The supported languages may not be complete. New languages will be added with
> each release. Additionally feel free to use the existing resource files to
> make your own translations.
>
> You could also use these resource files to rewrite existing translations. So
> you are not in need to create these files manually yourself.
## Limit the size of a validation message
Sometimes it is necessary to limit the maximum size a validation message can
have; as an example, when your view allows a maximum size of 100 chars to be
rendered on one line. To enable this, `Zend\Validator\AbstractValidator`
is able to automatically limit the maximum returned size of a validation
message.
To get the actual set size use `Zend\Validator\AbstractValidator::getMessageLength()`.
If it is `-1`, then the returned message will not be truncated. This is default
behaviour.
To limit the returned message size, use `Zend\Validator\AbstractValidator::setMessageLength()`.
Set it to any integer size you need. When the returned message exceeds the set
size, then the message will be truncated and the string `**...**` will be added
instead of the rest of the message.
```php
Zend\Validator\AbstractValidator::setMessageLength(100);
```
> ### Where is this parameter used?
>
> The set message length is used for all validators, even for self defined ones,
> as long as they extend `Zend\Validator\AbstractValidator`.

View File

@@ -0,0 +1,45 @@
# Standard Validation Classes
The following validators come with the zend-validator distribution.
- [Barcode](validators/barcode.md)
- [Between](validators/between.md)
- [Callback](validators/callback.md)
- [CreditCard](validators/credit-card.md)
- [Date](validators/date.md)
- [RecordExists and NoRecordExists (database)](validators/db.md)
- [Digits](validators/digits.md)
- [EmailAddress](validators/email-address.md)
- [File Validation Classes](validators/file/intro.md)
- [GreaterThan](validators/greater-than.md)
- [Hex](validators/hex.md)
- [Hostname](validators/hostname.md)
- [Iban](validators/iban.md)
- [Identical](validators/identical.md)
- [InArray](validators/in-array.md)
- [Ip](validators/ip.md)
- [Isbn](validators/isbn.md)
- [IsInstanceOf](validators/isinstanceof.md)
- [LessThan](validators/less-than.md)
- [NotEmpty](validators/not-empty.md)
- [PostCode](validators/post-code.md)
- [Regex](validators/regex.md)
- [Sitemap](validators/sitemap.md)
- [Step](validators/step.md)
- [StringLength](validators/string-length.md)
- [Timezone](validators/timezone.md)
- [Uri](validators/uri.md)
- [Uuid](validators/uuid.md)
## Additional validators
Several other components offer validators as well:
- [zend-i18n](http://zendframework.github.io/zend-i18n/validators/)
## Deprecated Validators
### Ccnum
The `Ccnum` validator has been deprecated in favor of the `CreditCard`
validator. For security reasons you should use `CreditCard` instead of `Ccnum`.

View File

@@ -0,0 +1,96 @@
# Validator Chains
Often, multiple validations should be applied to some value in a particular
order. The following code demonstrates a way to solve the example from the
[introduction](intro.md), where a username must be between 6 and 12 alphanumeric
characters:
```php
use Zend\I18n\Validator\Alnum;
use Zend\Validator\StringLength;
use Zend\Validator\ValidatorChain;
// Create a validator chain and add validators to it
$chain = new ValidatorChain();
$chain->attach(new StringLength(['min' => 6, 'max' => 12]));
$chain->attach(new Alnum());
// Validate the username
if ($validatorChain->isValid($username)) {
// username passed validation
} else {
// username failed validation; print reasons
foreach ($validatorChain->getMessages() as $message) {
echo "$message\n";
}
}
```
Validators are run in the order they were added to the `ValidatorChain`. In the
above example, the username is first checked to ensure that its length is
between 6 and 12 characters, and then it is checked to ensure that it contains
only alphanumeric characters. The second validation, for alphanumeric
characters, is performed regardless of whether the first validation, for length
between 6 and 12 characters, succeeds. This means that if both validations fail,
`getMessages()` will return failure messages from both validators.
In some cases, it makes sense to have a validator *break the chain* if its
validation process fails. `ValidatorChain` supports such use cases with the
second parameter to the `attach()` method. By setting `$breakChainOnFailure` to
`true`, if the validator fails, it will short-circuit execution of the chain,
preventing subsequent validators from executing. If the above example were
written as follows, then the alphanumeric validation would not occur if the
string length validation fails:
```php
$chain->attach(new StringLength(['min' => 6, 'max' => 12], true));
$chain->attach(new Alnum());
```
Any object that implements `Zend\Validator\ValidatorInterface` may be used in a
validator chain.
## Setting Validator Chain Order
For each validator added to the `ValidatorChain`, you can set a *priority* to
define the chain order. The default value is `1`. Higher values indicate earlier
execution, while lower values execute later; use negative values to force late
execution.
In the following example, the username is first checked to ensure that its
length is between 7 and 9 characters, and then it is checked to ensure that its
length is between 3 and 5 characters.
```php
use Zend\I18n\Validator\Alnum;
use Zend\Validator\StringLength;
use Zend\Validator\ValidatorChain;
$username = 'ABCDFE';
// Create a validator chain and add validators to it
$chain = new ValidatorChain();
$chain->attach(
new StringLength(['min' => 3, 'max' => 5]),
true, // break chain on failure
1
);
$chain->attach(
new StringLength(['min' => 7, 'max' => 9]),
true, // break chain on failure
2 // higher priority!
);
// Validate the username
if ($validatorChain->isValid($username)) {
// username passed validation
echo "Success";
} else {
// username failed validation; print reasons
foreach ($validatorChain->getMessages() as $message) {
echo "$message\n";
}
}
// This first example will display: The input is less than 7 characters long
```

View File

@@ -0,0 +1,358 @@
# Barcode Validator
`Zend\Validator\Barcode` allows you to check if a given value can be represented
as a barcode.
## Supported barcodes
`Zend\Validator\Barcode` supports multiple barcode standards and can be extended
with proprietary barcode implementations. 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
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 must know its type. See the
following example for an EAN13 barcode:
```php
$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.
```php
$valid = new Zend\Validator\Barcode([
'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\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.
```php
namespace My\Barcode;
use Zend\Validator\Barcode;
use Zend\Validator\Barcode\AbstractAdapter;
class MyBar extends AbstractAdapter
{
protected $length = 'even';
protected $characters = '0123456789ABCDE';
protected $checksum = 'mod66';
protected function mod66($barcode)
{
// do some validations and return a boolean
}
}
$valid = Barcode(MyBar::class);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```

View File

@@ -0,0 +1,54 @@
# Between Validator
`Zend\Validator\Between` allows you to validate if a given value is between two
other values.
> ### Only supports number validation
>
> `Zend\Validator\Between` supports only the validation of numbers. Strings or
> dates can not be validated with this validator.
## Supported options
The following options are supported for `Zend\Validator\Between`:
- `inclusive`: Defines if the validation is inclusive of 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
Per default, this validator checks if a value is between `min` and `max` where
both border values are allowed as value.
```php
$valid = new Zend\Validator\Between(['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 the default
search is inclusive of the border values. This means in our case that any value
from '0' to '10' is allowed; values like '-1' and '11' will return `false`.
## Excluding border values
Sometimes it is useful to validate a value by excluding the border values. See
the following example:
```php
$valid = new Zend\Validator\Between([
'min' => 0,
'max' => 10,
'inclusive' => false,
]);
$value = 10;
$result = $valid->isValid($value);
// returns false
```
The example above is almost identical to our first example, but we now exclue
the border values; as such, the values '0' and '10' are no longer allowed and
will return `false`.

View File

@@ -0,0 +1,203 @@
# Callback Validator
`Zend\Validator\Callback` allows you to provide a callback with which to
validate a given value.
## Supported options
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 validator
and/or callback.
## Basic usage
The simplest use case is to pass a function as a callback. Consider the
following function:
```php
function myMethod($value)
{
// some validation
return true;
}
```
To use it within `Zend\Validator\Callback`, pass it to the constructor
```php
$valid = new Zend\Validator\Callback('myMethod');
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
## Usage with closures
The `Callback` validator supports any PHP callable, including PHP
[closures](http://php.net/functions.anonymous).
```php
$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. Consider the
following class definition:
```php
class MyClass
{
public function myMethod($value)
{
// some validation
return true;
}
}
```
To use it with the `Callback` validator, pass a callable using an instance of
the class:
```php
$valid = new Zend\Validator\Callback([new MyClass, '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:
```php
class MyClass
{
public static function test($value)
{
// some validation
return true;
}
}
$valid = new Zend\Validator\Callback(MyClass::class, 'test']);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
Finally, you may define the magic method `__invoke()` in your class. If you do
so, you can provide a class instance itself as the callback:
```php
class MyClass
{
public function __invoke($value)
{
// some validation
return true;
}
}
$valid = new Zend\Validator\Callback(new MyClass());
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:
```php
class MyClass
{
public static function myMethod($value, $option)
{
// some validation
return true;
}
/**
* Or, to use with contextual validation
*/
public static function myMethod($value, $context, $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 `callbackOptions`:
```php
$valid = new Zend\Validator\Callback([
'callback' => [MyClass::class, 'myMethod'],
'callbackOptions' => $options,
]);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
Otherwise, you may pass them to the validator after instantiation:
```php
$valid = new Zend\Validator\Callback([MyClass::class, 'myMethod']);
$valid->setOptions($options);
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
passed as an additional argument:
```php
$valid = new Zend\Validator\Callback([MyClass::class, 'myMethod']);
$valid->setOptions($options);
if ($valid->isValid($input, $context)) {
// 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.

View File

@@ -0,0 +1,172 @@
# CreditCard Validator
`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` 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 and Canada
- Discover Card
- JCB
- Laser
- Maestro
- MasterCard
- Solo
- Visa
- Visa Electron
> ### Invalid institutes
>
> The institutes **Bankcard** and **Diners Club enRoute** no longer exist, and
> are treated as invalid.
>
> **Switch** has been rebranded to **Visa** and is therefore also treated as
> invalid.
## Supported options
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:
```php
$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 only specific credit cards
Sometimes it is necessary to accept only specific 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:
```php
use Zend\Validator\CreditCard;
$valid = new CreditCard(CreditCard::AMERICAN_EXPRESS);
```
When you want to allow multiple institutes, then you can provide them as array:
```php
use Zend\Validator\CreditCard;
$valid = new CreditCard([
CreditCard::AMERICAN_EXPRESS,
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 demostrated here:
```php
use Zend\Validator\CreditCard;
$valid = new CreditCard([
'type' => [CreditCard::AMERICAN_EXPRESS]
]);
```
You can also manipulate institutes after instantiation by using the methods
`setType()`, `addType()`, and `getType()`.
```php
use Zend\Validator\CreditCard;
$valid = new CreditCard();
$valid->setType([
CreditCard::AMERICAN_EXPRESS,
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 using 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, provide a callback to invoke when 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 instantiatio.
For details about possible options, read the
[Callback validator documentation](callback.md).
```php
use Zend\Validator\CreditCard;
// Your service class
class CcService
{
public function checkOnline($cardnumber, $types)
{
// some online validation
}
}
// The validation
$service = new CcService();
$valid = new CreditCard(CreditCard::VISA);
$valid->setService([$service, 'checkOnline']);
```
The callback method will be called with the credit card number as the first
parameter, and the accepted types as the second parameter.

View File

@@ -0,0 +1,35 @@
# Date Validator
`Zend\Validator\Date` allows you to validate if a given value contains a date.
## Supported options
The following options are supported for `Zend\Validator\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,
`Y-m-d`.
```php
$validator = new Zend\Validator\Date();
$validator->isValid('2000-10-10'); // returns true
$validator->isValid('10.10.2000'); // returns false
```
## Specifying a date format
`Zend\Validator\Date` also supports custom date formats. When you want to
validate such a date, use the `format` option. This option accepts any format
allowed by the PHP [date()](http://php.net/date) function.
```php
$validator = new Zend\Validator\Date(['format' => 'Y']);
$validator->isValid('2010'); // returns true
$validator->isValid('May'); // returns false
```

View File

@@ -0,0 +1,180 @@
# Db\\RecordExists and Db\\NoRecordExists Validators
`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
The following options are supported for `Zend\Validator\Db\NoRecordExists` and
`Zend\Validator\Db\RecordExists`:
- `adapter`: The database adapter that will be used for the search.
- `exclude`: Sets records that will be excluded from the search.
- `field`: The database field within this table that will be searched for the record.
- `schema`: Sets the schema that will be used for the search.
- `table`: The table that will be searched for the record.
## Basic usage
An example of basic usage of the validators:
```php
// Check that the email address exists in the database
$validator = new Zend\Validator\Db\RecordExists([
'table' => 'users',
'field' => 'emailaddress',
'adapter' => $dbAdapter,
]);
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.
```php
// Check that the username is not present in the database
$validator = new Zend\Validator\Db\NoRecordExists([
'table' => 'users',
'field' => 'username',
'adapter' => $dbAdapter,
]);
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)
```php
// Check no other users have the username
$user_id = $user->getId();
$validator = new Zend\Validator\Db\NoRecordExists([
'table' => 'users',
'field' => 'username',
'exclude' => [
'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.
```php
$email = 'user@example.com';
$clause = $dbAdapter->quoteIdentifier('email') . ' = ' . $dbAdapter->quoteValue($email);
$validator = new Zend\Validator\Db\RecordExists([
'table' => 'users',
'field' => 'username',
'adapter' => $dbAdapter,
'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 Schemas
You can specify a schema within your database for adapters such as PostgreSQL
and DB/2 by supplying an array with `table` and `schema` keys, as demonstrated
below:
```php
$validator = new Zend\Validator\Db\RecordExists([
'table' => 'users',
'schema' => 'my',
'field' => 'id',
]);
```
## Using a Select object
It is also possible to supply the validators with a `Zend\Db\Sql\Select` object
in place of options. The validator then uses this object instead of building its
own. This allows for greater flexibility with selection of records used for
validation.
```php
use Zend\Db\Sql\Select;
use Zend\Validator\Db\RecordExists;
$select = new Select();
$select
->from('users')
->where->equalTo('id', $user_id)
->where->equalTo('email', $email);
$validator = new RecordExists($select);
// We still need to set our database adapter
$validator->setAdapter($dbAdapter);
// Validation is then performed as usual
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.

View File

@@ -0,0 +1,27 @@
# Digits Validator
`Zend\Validator\Digits` validates if a given value contains only digits.
## Supported options
There are no additional options for `Zend\Validator\Digits`:
## Validating digits
To validate if a given value contains only digits and no other characters,
call the validator as shown below:
```php
$validator = new Zend\Validator\Digits();
$validator->isValid("1234567890"); // returns true
$validator->isValid(1234); // returns true
$validator->isValid('1a234'); // returns false
```
> ### Validating numbers
>
> When you want to validate numbers or numeric values, be aware that this
> validator only validates *digits*. This means that any other sign like a
> thousand separator or a comma will not pass this validator. In this case you
> should use `Zend\I18n\Validator\IsInt` or `Zend\I18n\Validator\IsFloat`.

View File

@@ -0,0 +1,201 @@
# EmailAddress Validator
`Zend\Validator\EmailAddress` allows you to validate an email address. The
validator first splits the email address on `local-part @ hostname` and attempts
to match these against known specifications for email addresses and hostnames.
## Basic usage
A basic example of usage is below:
```php
$validator = new Zend\Validator\EmailAddress();
if ($validator->isValid($email)) {
// email appears to be valid
} else {
// email is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
```
This will match the email address `$email` and on failure populate
`getMessages()` with useful error messages.
## Supported Options
`Zend\Validator\EmailAddress` supports several options which can either be set
at instantiation, 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 information about possible values of this option, look at
[Hostname](hostname.md) and possible `ALLOW_*` constants. This option
defaults to `ALLOW_DNS`.
- `deep`: Defines if the servers MX records should be verified by a deep check.
When this option is set to `true` then additionally to MX records also the `A`,
`A6` and `AAAA` records are used to verify if the server accepts emails. This
option defaults to `false`.
- `domain`: Defines if the domain part should be checked. When this option is
set to `false`, then only the local part of the email address will be checked.
In this case the hostname validator will not be called. This option defaults
to `true`.
- `hostname`: Sets the hostname validator with which the domain part of the
email address will be validated.
- `mx`: Defines if the MX records from the server should be detected. If this
option is defined to `true` then the MX records are used to verify if the
server accepts emails. This option defaults to `false`.
## Complex local parts
`Zend\Validator\EmailAddress` will match any valid email address according to
RFC2822. For example, valid emails include `bob@domain.com`,
`bob+jones@domain.us`, `"bob@jones"@domain.com*` and `"bob jones"@domain.com`
Some obsolete email formats will not currently validate (e.g. carriage returns
or a `\\` character in an email address).
## Validating only the local part
If you need `Zend\Validator\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\Validator\EmailAddress` not to
validate the hostname part of the email address.
```php
$validator = new Zend\Validator\EmailAddress();
$validator->setOptions(['domain' => FALSE]);
```
## Validating different types of hostnames
The hostname part of an email address is validated against the [Hostname validator](hostname.md).
By default only DNS hostnames of the form `domain.com` are accepted, though if
you wish you can accept IP addresses and Local hostnames too.
To do this you need to instantiate `Zend\Validator\EmailAddress` passing a
parameter to indicate the type of hostnames you want to accept. More details are
included in `Zend\Validator\Hostname`, though an example of how to accept both
DNS and Local hostnames appears below:
```php
use Zend\Validator\EmailAddress;
use Zend\Validator\Hostname;
$validator = new EmailAddress( Hostname::ALLOW_DNS | Hostname::ALLOW_LOCAL);
if ($validator->isValid($email)) {
// email appears to be valid
} else {
// email is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
```
## Checking if the hostname actually accepts email
Just because an email address is in the correct format, it doesn't necessarily
mean that email address actually exists. To help solve this problem, you can use
MX validation to check whether an MX (email) entry exists in the DNS record for
the email's hostname. This tells you that the hostname accepts email, but
doesn't tell you the exact email address itself is valid.
MX checking is not enabled by default. To enable MX checking you can pass a
second parameter to the `Zend\Validator\EmailAddress` constructor.
```php
$validator = new Zend\Validator\EmailAddress([
'allow' => Zend\Validator\Hostname::ALLOW_DNS,
'useMxCheck' => true,
]);
```
Alternatively you can either pass `true` or `false` to `setValidateMx()` to
enable or disable MX validation.
By enabling this setting, network functions will be used to check for the
presence of an MX record on the hostname of the email address you wish to
validate. Please be aware this will likely slow your script down.
Sometimes validation for MX records returns `false`, even if emails are
accepted. The reason behind this behaviour is, that servers can accept emails
even if they do not provide a MX record. In this case they can provide `A`,
`A6`, or `AAAA` records. To allow `Zend\Validator\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()`.
```php
$validator = new Zend\Validator\EmailAddress([
'allow' => Zend\Validator\Hostname::ALLOW_DNS,
'useMxCheck' => true,
'useDeepMxCheck' => true,
]);
```
Sometimes it can be useful to get the server's MX information which have been
used to do further processing. Simply use `getMXRecord()` after validation. This
method returns the received MX record including weight and sorted by it.
> ### 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.
> ### 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\Validator\EmailAddress` will also match international characters that
exist in some domains. This is known as International Domain Name (IDN) support.
This is enabled by default, though you can disable this by changing the setting
via the internal `Zend\Validator\Hostname` object that exists within
`Zend\Validator\EmailAddress`.
```php
$validator->getHostnameValidator()->setValidateIdn(false);
```
More information on the usage of `setValidateIdn()` appears in the
[Hostname documentation](hostname.md).
Please note IDNs are only validated if you allow DNS hostnames to be validated.
## Validating Top Level Domains
By default a hostname will be checked against a list of known TLDs. This is
enabled by default, though you can disable this by changing the setting via the
internal `Zend\Validator\Hostname` object that exists within
`Zend\Validator\EmailAddress`.
```php
$validator->getHostnameValidator()->setValidateTld(false);
```
More information on the usage of `setValidateTld()` appears in the
[Hostname documentation](hostname.md).
Please note TLDs are only validated if you allow DNS hostnames to be validated.
## Setting messages
`Zend\Validator\EmailAddress` makes also use of `Zend\Validator\Hostname` to
check the hostname part of a given email address. You can specify messages for
`Zend\Validator\Hostname` from within `Zend\Validator\EmailAddress`.
```php
$validator = new Zend\Validator\EmailAddress();
$validator->setMessages([
Zend\Validator\Hostname::UNKNOWN_TLD => 'I don\'t know the TLD you gave'
]);
```

View File

@@ -0,0 +1,31 @@
# Count
`Zend\Validator\File\Count` allows you to validate that the number of files
uploaded matches criteria, including a minimum number of files and/or a maximum
number of files.
## Supported Options
The following options are supported:
- `min`: The minimum number of uploaded files acceptable; `null` is equivalent
to `0`, indicating no minimum.
- `max`: The maximum number of uploaded files acceptable; `null` is equivalent
to no maximum.
## Basic Usage
```php
$validator = new Zend\Validator\File\Count([
'min' => 1,
'max' => 5,
]);
// Setting to the $_FILES superglobal; could also use the zend-http
// request's `getFiles()` or PSR-7 ServerRequest's `getUploadedFiles()`.
$files = $_FILES;
if ($validator->isValid($files)) {
// Received between 1 and 5 files!
}
```

View File

@@ -0,0 +1,60 @@
# Crc32
`Zend\Validator\File\Crc32` allows you to validate if a given file's hashed
contents matches the supplied crc32 hash(es). It is subclassed from the [Hash
validator](hash.md) to provide a validator that only supports the `crc32`
algorithm.
> ### Requires the hash extension
>
> This validator requires the PHP [Hash extension](http://php.net/hash) with the
> `crc32` algorithm.
## Supported Options
The following options are supported:
- `hash`: Single string hash to test the file against, or array of filename/hash
pairs.
## Usage Examples
```php
// Does file have the given hash?
$validator = new \Zend\Validator\File\Crc32('3b3652f');
// Or, check file against multiple hashes
$validator = new \Zend\Validator\File\Crc32(array('3b3652f', 'e612b69'));
// Perform validation with file path
if ($validator->isValid('./myfile.txt')) {
// file is valid
}
```
## Public Methods
### getCrc32
```php
getCrc32() : array
```
Returns an array of all currently registered hashes to test against.
### addCrc32
```php
addCrc32(string|array $options) : void
```
Add a single hash to test against, or a set of filename/hash pairs to test
against.
### setCrc32
```php
setCrc32(string|array $options): void
```
Overwrite the current list of registered hashes with the one(s) provided.

View File

@@ -0,0 +1,7 @@
# ExcludeExtension
`Zend\Validator\File\ExcludeExtension` checks the extension of files. It will
assert `false` when a given file matches any of the defined extensions.
This validator is inversely related to the [Extension validator](extension.md);
please refer to that validator for full options and usage examples.

View File

@@ -0,0 +1,9 @@
ExcludeMimeType
===============
`Zend\Validator\File\ExcludeMimeType` checks the MIME type of files. It will
assert `false` when a given file matches any of the defined MIME types.
This validator is inversely related to the [MimeType validator](mime-type.md);
please refer to that validator's documentation for full options and usage
examples.

View File

@@ -0,0 +1,35 @@
# Exists
`Zend\Validator\File\Exists` checks for the existence of files in specified
directories.
This validator is inversely related to the [NotExists validator](not-exists.md).
## Supported Options
The following set of options are supported:
- `directory`: Array of directories, or comma-delimited string of directories.
## Usage Examples
```php
use Zend\Validator\File\Exists;
// Only allow files that exist in ~both~ directories
$validator = new Exists('/tmp,/var/tmp');
// ...or with array notation
$validator = new Exists(['/tmp', '/var/tmp']);
// Perform validation
if ($validator->isValid('/tmp/myfile.txt')) {
// file is valid
}
```
> ### Checks against all directories
>
> This validator checks whether the specified file exists in **all** of the
> given directories; validation will fail if the file does not exist in one
> or more of them.

View File

@@ -0,0 +1,52 @@
# Extension
`Zend\Validator\File\Extension` checks the extension of files. It will assert
`true` when a given file matches any of the defined extensions.
This validator is inversely related to the
[ExcludeExtension validator](exclude-extension.md).
## Supported Options
The following set of options are supported:
- `extension`: Array of extensions, or comma-delimited string of extensions,
against which to test.
- `case`: Boolean indicating whether or not extensions should match case
sensitively; defaults to `false` (case-insensitive).
## Usage Examples
```php
use Zend\Validator\File\Extension;
// Allow files with 'php' or 'exe' extensions
$validator = new Extension('php,exe');
// ...or with array notation
$validator = new Extension(['php', 'exe']);
// Test with case-sensitivity on
$validator = new Extension(['php', 'exe'], true);
// Using an options array:
$validator = new Extension([
'extension' => ['php', 'exe'],
'case' => true,
]);
// Perform validation
if ($validator->isValid('./myfile.php')) {
// file is valid
}
```
## Public Methods
### addExtension
```php
addExtension(string|array $options) : void
```
Add one or more extensions as a comma-separated list, or as an array.

View File

@@ -0,0 +1,38 @@
# FilesSize
`Zend\Validator\File\FilesSize` allows validating the total size of all file
uploads in aggregate, allowing specifying a minimum upload size and/or a maximum
upload size.
Only use this validator if you will be expecting multiple file uploads in a
single payload, and want to ensure the aggregate size falls within a specific
range.
## Supported Options
`Zend\Validator\File\FilesSize` supports the following options:
- `min`: The minimum aggregate size of all file uploads. May be specified as an
integer or using SI units. `null` indicates no minimum size is required.
- `max`: The maximum aggregate size of all file uploads. May be specified as an
integer or using SI units. `null` indicates no maximum size is required.
- `useByteString`: A flag indicating whether sizes should be reported as
integers or using SI units when reporting validation errors.
See the [Size validator](size.md#supported-options) for details on supported SI
units.
## Basic Usage
```php
use Zend\Validator\File\FilesSize;
$validator = new FilesSize([
'min' => '1kB`, // minimum of 1kB
'max' => `10MB', // maximum of 10MB
]);
if ($validator->isValid($_FILES)) {
// > 1kB, < 10MB in aggregate
}
```

View File

@@ -0,0 +1,66 @@
# Hash
`Zend\Validator\File\Hash` allows you to validate if a given file's hashed
contents matches the supplied hash(es) and algorithm(s).
> ### Requires the hash extension
>
> This validator requires the PHP [Hash extension](http://php.net/hash). A list
> of supported hash algorithms can be found with the
> [hash\_algos() function](http://php.net/hash_algos).
## Supported Options
The following set of options are supported:
- `hash`: String hash or array of hashes against which to test.
- `algorithm`: String hashing algorithm to use; defaults to `crc32`
## Basic Usage
```php
use Zend\Validator\File\Hash;
// Does file have the given hash?
$validator = new Hash('3b3652f', 'crc32');
// Or, check file against multiple hashes
$validator = new Hash(['3b3652f', 'e612b69'], 'crc32');
// Or use options notation:
$validator = new Hash([
'hash' => ['3b3652f', 'e612b69'],
'algorithm' => 'crc32',
]);
// Perform validation with file path
if ($validator->isValid('./myfile.txt')) {
// file is valid
}
```
## Public Methods
### getHash
```php
getHash() : array
```
Returns an array containing the set of hashes against which to validate.
### addHash
```php
addHash(string|array $options) : void
```
Add one or more hashes against which to validate.
### setHash
```php
setHash(string|array $options) : void
```
Overwrite the current set of hashes with those provided to the method.

View File

@@ -0,0 +1,71 @@
# ImageSize
`Zend\Validator\File\ImageSize` checks the size of image files. Minimum and/or
maximum dimensions can be set to validate against.
## Supported Options
The following set of options are supported:
- `minWidth`: Set the minimum image width as an integer; `null` (the default)
indicates no minimum.
- `minHeight`: Set the minimum image height as an integer; `null` (the default)
indicates no minimum.
- `maxWidth`: Set the maximum image width as an integer; `null` (the default)
indicates no maximum.
- `maxHeight`: Set the maximum image height as an integer; `null` (the default)
indicates no maximum.
## Basic Usage
```php
use Zend\Validator\File\ImageSize;
// Is image size between 320x200 (min) and 640x480 (max)?
$validator = new ImageSize(320, 200, 640, 480);
// ...or with array notation
$validator = new ImageSize([
'minWidth' => 320,
'minHeight' => 200,
'maxWidth' => 640,
'maxHeight' => 480,
]);
// Is image size equal to or larger than 320x200?
$validator = new ImageSize([
'minWidth' => 320,
'minHeight' => 200,
]);
// Is image size equal to or smaller than 640x480?
$validator = new ImageSize([
'maxWidth' => 640,
'maxHeight' => 480,
]);
// Perform validation with file path
if ($validator->isValid('./myfile.jpg')) {
// file is valid
}
```
## Public Methods
### getImageMin
```php
getImageMin() : array
```
Returns the minimum valid dimensions as an array with the keys `width` and
`height`.
### getImageMax
```php
getImageMax() : array
```
Returns the maximum valid dimensions as an array with the keys `width` and
`height`.

View File

@@ -0,0 +1,30 @@
# File Validation Classes
Zend Framework comes with a set of classes for validating both files and
uploaded files, such as file size validation and CRC checking.
- [Count](count.md)
- [crc32](crc32.md)
- [ExcludeExtension](exclude-extension.md)
- [ExcludeMimeType](exclude-mime-type.md)
- [Exists](exists.md)
- [Extension](extension.md)
- [FilesSize](files-size.md)
- [Hash](hash.md)
- [ImageSize](image-size.md)
- [IsCompressed](is-compressed.md)
- [IsImage](is-image.md)
- [Md5](md5.md)
- [MimeType](mime-type.md)
- [NotExists](not-exists.md)
- [Sha1](sha1.md)
- [Size](size.md)
- [Upload](upload.md)
- [UploadFile](upload-file.md)
- [WordCount](word-count.md)
> ### Validation argument
>
> All of the File validators' `isValid()` methods support both a file path
> `string` *or* a `$_FILES` array as the supplied argument. When a `$_FILES`
> array is passed in, the `tmp_name` is used for the file path.

View File

@@ -0,0 +1,21 @@
# IsCompressed
`Zend\Validator\File\IsCompressed` checks if a file is a compressed archive,
such as zip or gzip. This validator is based on the
[MimeType validator](mime-type.md), and supports the same methods and options.
The default list of [compressed file MIME types](https://github.com/zendframework/zend-validator/blob/master/src/File/IsCompressed.php#L45)
can be found in the source code.
Please refer to the [MimeType validator](mime-type.md) for options and public
methods.
## Basic Usage
```php
$validator = new \Zend\Validator\File\IsCompressed();
if ($validator->isValid('./myfile.zip')) {
// file is valid
}
```

View File

@@ -0,0 +1,21 @@
# IsImage
`Zend\Validator\File\IsImage` checks if a file is an image, such as jpg or png.
This validator is based on the [MimeType validator](mime-type.md) and supports
the same methods and options.
The default list of [image file MIME types](https://github.com/zendframework/zend-validator/blob/master/src/File/IsImage.php#L44)
can be found in the source code.
Please refer to the [MimeType validator](mime-type.md) for options and public
methods.
## Basic Usage
```php
$validator = new Zend\Validator\File\IsImage();
if ($validator->isValid('./myfile.jpg')) {
// file is valid
}
```

View File

@@ -0,0 +1,68 @@
# Md5
`Zend\Validator\File\Md5` allows you to validate if a given file's hashed
contents matches the supplied md5 hash(es). It is subclassed from the
[Hash validator](hash.md) to provide a validator that supports only the MD5
algorithm.
> ### Requires the hash extension
>
> This validator requires the PHP [Hash extension](http://php.net/hash) PHP with
> the `md5` algorithm.
## Supported Options
The following set of options are supported:
- `hash`: String hash or array of hashes against which to validate.
## Basic Usage
```php
use Zend\Validator\File\Md5;
// Does file have the given hash?
$validator = new Md5('3b3652f336522365223');
// Or, check file against multiple hashes
$validator = new Md5([
'3b3652f336522365223', 'eb3365f3365ddc65365'
]);
// Or use options notation:
$validator = new Md5(['hash' => [
'3b3652f336522365223', 'eb3365f3365ddc65365'
]]);
// Perform validation with file path
if ($validator->isValid('./myfile.txt')) {
// file is valid
}
```
## Public Methods
### getMd5
```php
getMd5() : array
```
Returns an array of MD5 hashes against which to validate.
### addMd5
```php
addMd5(string|array $options) : void
```
Add one or more hashes to validate against.
### setMd5
```php
setMd5(string|array $options) : void
```
Overwrite any previously set hashes with those specified.

View File

@@ -0,0 +1,68 @@
# MimeType
`Zend\Validator\File\MimeType` checks the MIME type of files. It will assert
`true` when a given file matches any defined MIME type.
This validator is inversely related to the
[ExcludeMimeType validator](exclude-mime-type.md)
> ### Compatibility
>
> This component will use the `FileInfo` extension if it is available. If it's
> not, it will degrade to the `mime_content_type()` function. And if the
> function call fails, it will use the MIME type which is given by HTTP. You
> should be aware of possible security problems when you do not have `FileInfo`
> or `mime_content_type()` available; the MIME type given by HTTP is not secure
> and can be easily manipulated.
## Supported Options
The following set of options are supported:
- `mimeType`: Comma-delimited string of MIME types, or array of MIME types,
against which to test. Types can be specific (e.g., `image/jpg`), or refer
only to the group (e.g., `image`).
- `magicFile`: Location of the magicfile to use for MIME type comparisons;
defaults to the value of the `MAGIC` constant.
- `enableHeaderCheck`: Boolean flag indicating whether or not to use HTTP
headers when determining the MIME type if neither the `FileInfo` nor
`mime_magic` extensions are available; defaults to `false`.
## Basic Usage
```php
use Zend\Validator\File\MimeType;
// Only allow 'gif' or 'jpg' files
$validator = new MimeType('image/gif,image/jpg');
// ... or with array notation:
$validator = new MimeType(['image/gif', 'image/jpg']);
// ... or restrict to entire group of types:
$validator = new MimeType(['image', 'audio']);
// Specify a different magicFile:
$validator = new MimeType([
'mimeType' => ['image/gif', 'image/jpg'],
'magicFile' => '/path/to/magicfile.mgx',
]);
// Enable HTTP header scanning (do not do this!):
$validator = new MimeType([
'mimeType' => ['image/gif', 'image/jpg'],
'enableHeaderCheck' => true,
]);
// Perform validation
if ($validator->isValid('./myfile.jpg')) {
// file is valid
}
```
> ### Validating MIME groups is potentially dangerous
>
> Allowing "groups" of MIME types will accept **all** members of this group, even
> if your application does not support them. For instance, When you allow
> `image` you also allow `image/xpixmap` and `image/vasa`, both of which could
> be problematic.

View File

@@ -0,0 +1,42 @@
# NotExists
`Zend\Validator\File\NotExists` checks for the existence of files in specified
directories.
This validator is inversely related to the [Exists validator](exists.md).
## Supported Options
The following set of options are supported:
- `directory`: Array of directories or comma-delimited string of directories
against which to validate.
## Basic Usage
```php
use Zend\Validator\File\NotExists;
// Only allow files that do not exist in ~either~ directories
$validator = new NotExists('/tmp,/var/tmp');
// ... or with array notation:
$validator = new NotExists(['/tmp', '/var/tmp']);
// ... or using options notation:
$validator = new NotExists(['directory' => [
'/tmp',
'/var/tmp',
]]);
// Perform validation
if ($validator->isValid('/home/myfile.txt')) {
// file is valid
}
```
> ### Checks against all directories
>
> This validator checks whether the specified file does not exist in **any** of
> the given directories; validation will fail if the file exists in one (or
> more) of the given directories.

View File

@@ -0,0 +1,69 @@
# Sha1
`Zend\Validator\File\Sha1` allows you to validate if a given file's hashed
contents matches the supplied sha1 hash(es). It is subclassed from the
[Hash validator](hash.md) to provide a validator that only supports the `sha1`
algorithm.
> ### Requires the hash extension
>
> This validator requires the PHP [Hash extension](http://php.net/hash) with the
> `sha1` algorithm.
## Supported Options
The following set of options are supported:
- `hash`: String hash or array of hashes against which to validate.
## Basic Usage
```php
use Zend\Validator\File\Sha1;
// Does file have the given hash?
$validator = new Sha1('3b3652f336522365223');
// Or check file against multiple hashes:
$validator = new Sha1([
'3b3652f336522365223',
'eb3365f3365ddc65365',
]);
// Or using options notation:
$validator = new Sha1(['hash' => [
'3b3652f336522365223',
'eb3365f3365ddc65365',
]]);
// Perform validation with file path
if ($validator->isValid('./myfile.txt')) {
// file is valid
}
```
## Public Methods
### getSha1
```php
getSha1() : array
```
Returns an array of sha1 hashes against which to validate.
### addSha1
```php
addSha1(string|array $options) : void
```
Add one or more hashes to validate against.
### setSha1
```php
setSha1(string|array $options) : void
```
Overwrite any previously set hashes with those specified.

View File

@@ -0,0 +1,37 @@
# Size
`Zend\Validator\File\Size` checks for the size of a file.
## Supported Options
The following set of options are supported:
- `min`: Minimum file size in integer bytes, or in string SI notation; `null`
indicates no minimum required.
- `max`: maximum file size in integer bytes, or in string SI notation; `null`
indicates no maximum required.
- `useByteString`: Boolean flag indicating whether to dispaly error messages
using SI notation (default, `true`), or in bytes (`false`).
SI units supported are: kB, MB, GB, TB, PB, and EB. All sizes are converted
using 1024 as the base value (ie. 1kB == 1024 bytes, 1MB == 1024kB).
## Basic Usage
```php
use Zend\Validator\File\Size;
// Limit the file size to 40000 bytes
$validator = new Size(40000);
// Limit the file size to between 10kB and 4MB
$validator = new Size([
'min' => '10kB',
'max' => '4MB',
]);
// Perform validation with file path
if ($validator->isValid('./myfile.txt')) {
// file is valid
}
```

View File

@@ -0,0 +1,25 @@
# UploadFile
`Zend\Validator\File\UploadFile` checks whether a single file has been uploaded
via a form `POST` and will return descriptive messages for any upload errors.
# Basic Usage
```php
use Zend\Http\PhpEnvironment\Request;
use Zend\Validator\File\UploadFile;
$request = new Request();
$files = $request->getFiles();
// i.e. $files['my-upload']['error'] == 0
$validator = new UploadFile();
if ($validator->isValid($files['my-upload'])) {
// file is valid
}
```
## Usage with zend-inputfilter
When using zend-inputfilter's [FileInput](https://zendframework.github.io/zend-inputfilter/file-input/),
this validator will be automatically prepended to the validator chain.

View File

@@ -0,0 +1,30 @@
# Upload
`Zend\Validator\File\Upload` validates that a file upload operation was
successful.
## Supported Options
`Zend\Validator\File\Upload` supports the following options:
- `files`: array of file uploads. This is generally the `$_FILES` array, but
should be normalized per the details in [PSR-7](http://www.php-fig.org/psr/psr-7/#1-6-uploaded-files)
(which is also how [the zend-http Request](https://zendframework.github.io/zend-http)
normalizes the array).
## Basic Usage
```php
use Zend\Validator\File\Upload;
// Using zend-http's request:
$validator = new Upload($request->getFiles());
// Or using options notation:
$validator = new Upload(['files' => $request->getFiles()]);
// Validate:
if ($validator->isValid('foo')) {
// "foo" file upload was successful
}
```

View File

@@ -0,0 +1,34 @@
# WordCount
`Zend\Validator\File\WordCount` validates that the number of words within a file
match the specified criteria.
## Supported Options
The following set of options are supported:
- `min`: the minimum number of words required; `null` indicates no minimum.
- `max`: the maximum number of words required; `null` indicates no maximum.
## Basic Usage
```php
use Zend\Validator\File\WordCount;
// Limit the amount of words to a maximum of 2000:
$validator = new WordCount(2000);
// Limit the amount of words to between 100 and 5000:
$validator = new WordCount(100, 5000);
// ... or use options notation:
$validator = new WordCount([
'min' => 1000,
'max' => 5000,
]);
// Perform validation with file path
if ($validator->isValid('./myfile.txt')) {
// file is valid
}
```

View File

@@ -0,0 +1,48 @@
# GreaterThan Validator
`Zend\Validator\GreaterThan` allows you to validate if a given value is greater
than a minimum border value.
> ### Only supports numbers
>
> `Zend\Validator\GreaterThan` supports only the validation of numbers. Strings
> or dates can not be validated with this validator.
## Supported options
The following options are supported for `Zend\Validator\GreaterThan`:
- `inclusive`: Defines if the validation is inclusive of the minimum value,
or exclusive. It defaults to `false`.
- `min`: Sets the minimum allowed value.
## Basic usage
To validate if a given value is greater than a defined minimum:
```php
$valid = new Zend\Validator\GreaterThan(['min' => 10]);
$value = 8;
$return = $valid->isValid($value);
// returns false
```
The above example returns `true` for all values which are greater than 10.
## Inclusive validation
Sometimes it is useful to validate a value by including the minimum value.
```php
$valid = new Zend\Validator\GreaterThan([
'min' => 10,
'inclusive' => true,
]);
$value = 10;
$result = $valid->isValid($value);
// returns true
```
The example is identical to our first example, with the exception that we
included the minimum value. Now the value '10' is allowed and will return
`true`.

View File

@@ -0,0 +1,25 @@
# Hex Validator
`Zend\Validator\Hex` allows you to validate if a given value contains only
hexadecimal characters. These are all characters from **0 to 9** and **A to F**,
case insensitive. There is no length limitation for the input you want to
validate.
```php
$validator = new Zend\Validator\Hex();
if ($validator->isValid('123ABC')) {
// value contains only hex chars
} else {
// false
}
```
> ### Invalid characters
>
> All other characters will return false, including whitespace and decimal
> points. Additionally, unicode zeros and numbers from other scripts than latin
> will not be treated as valid.
## Supported options
There are no additional options for `Zend\Validator\Hex`.

View File

@@ -0,0 +1,142 @@
# Hostname Validator
`Zend\Validator\Hostname` allows you to validate a hostname against a set of
known specifications. It is possible to check for three different types of
hostnames: a DNS Hostname (i.e. `domain.com`), IP address (i.e. 1.2.3.4), and
Local hostnames (i.e. localhost). By default, only DNS hostnames are matched.
## Supported options
The following options are supported for `Zend\Validator\Hostname`:
- `allow`: Defines the sort of hostname which is allowed to be used.
[See below](#validating-different-types-of-hostnames) for details.
- `idn`: Defines if IDN domains are allowed or not. This option defaults to
`true`.
- `ip`: Allows defining a custom IP validator. This option defaults to a new
instance of `Zend\Validator\Ip`.
- `tld`: Defines if TLDs are validated. This option defaults to `true`.
## Basic usage
```php
$validator = new Zend\Validator\Hostname();
if ($validator->isValid($hostname)) {
// hostname appears to be valid
} else {
// hostname is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
```
This will match the hostname `$hostname` and on failure populate `getMessages()`
with useful error messages.
## Validating different types of hostnames
You may find you also want to match IP addresses, Local hostnames, or a
combination of all allowed types. This can be done by passing a parameter to
`Zend\Validator\Hostname` when you instantiate it. The parameter should be an
integer which determines what types of hostnames are allowed. You are encouraged
to use the `Zend\Validator\Hostname` constants to do this.
The `Zend\Validator\Hostname` constants are:
- `ALLOW_DNS`, to allow only DNS hostnames
- `ALLOW_IP` to allow IP addresses
- `ALLOW_LOCAL` to allow local network names
- `ALLOW_URI` to allow [RFC3986](http://tools.ietf.org/html/rfc3986)-compliant addresses
- `ALLOW_ALL` to allow all four above types
> ### Additional Information on `ALLOW_URI`
>
> `ALLOW_URI` allows checking hostnames according to
> [RFC3986](http://tools.ietf.org/html/rfc3986). These are registered names
> which are used by WINS, NetInfo and also local hostnames like those defined
> within your `hosts` file.
To check for IP addresses only, you can use the example below:
```php
use Zend\Validator\Hostname;
$validator = new Hostname(Hostname::ALLOW_IP);
if ($validator->isValid($hostname)) {
// hostname appears to be valid
} else {
// hostname is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
```
As well as using `ALLOW_ALL` to accept all common hostnames types, you can
combine these types to allow for combinations. For example, to accept DNS and
Local hostnames:
```php
use Zend\Validator\Hostname;
$validator = new Hostname(Hostname::ALLOW_DNS | Hostname::ALLOW_IP);
```
## Validating International Domains Names
Some Country Code Top Level Domains (ccTLDs), such as 'de' (Germany), support
international characters in domain names. These are known as International
Domain Names (IDN). These domains can be matched by `Zend\Validator\Hostname`
via extended characters that are used in the validation process.
At the time of writing, more than 50 ccTLDs support IDN domains.
The `Hostname` validator matches IDN domains by default. If you wish to disable
IDN validation, either pass a parameter to the `Zend\Validator\Hostname`
constructor or call the `setValidateIdn()` method.
You can disable IDN validation by passing a second parameter to the
`Zend\Validator\Hostname` constructor in the following way.
```php
$validator = new Zend\Validator\Hostname([
'allow' => Zend\Validator\Hostname::ALLOW_DNS,
'useIdnCheck' => false,
]);
```
Alternatively you can either pass `true` or `false` to `setValidateIdn()` to
enable or disable IDN validation. If you are trying to match an IDN hostname
which isn't currently supported, it is likely it will fail validation if it has
any international characters in it. Where a ccTLD file doesn't exist in
`Zend/Validator/Hostname` specifying the additional characters, a normal hostname
validation is performed.
Please note that IDNs are only validated if you allow DNS hostnames to be
validated.
## Validating Top Level Domains
By default, a hostname will be verified against a list of known TLDs. If this
functionality is not required, it can be disabled in much the same way as
disabling IDN support. You can disable TLD validation by passing a third
parameter to the `Zend\Validator\Hostname` constructor. In the example below we
are supporting IDN validation via the second parameter.
```php
use Zend\Validator\Hostname;
$validator = new Hostname([
'allow' => Hostname::ALLOW_DNS,
'useIdnCheck' => true,
'useTldCheck' => false,
]);
```
Alternatively you can either pass `true` or `false` to `setValidateTld()` to
enable or disable TLD validation.
Please note, TLDs are only validated if you allow DNS hostnames to be validated.

View File

@@ -0,0 +1,55 @@
# Iban Validator
`Zend\Validator\Iban` validates if a given value could be a IBAN number. IBAN is
the abbreviation for "International Bank Account Number".
## Supported options
The following options are supported for `Zend\Validator\Iban`:
- `country_code`: Sets the country code 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 country code. By knowing this we already know how
to use `Zend\Validator\Iban`.
### Ungreedy IBAN validation
Sometime it is useful 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 `false` as locale.
```php
$validator = new Zend\Validator\Iban(['country_code' => false]);
// Note: you can also provide FALSE as the sole parameter
if ($validator->isValid('AT611904300234573201')) {
// IBAN appears to be valid
} else {
// IBAN is not valid
}
```
In this situation, any IBAN number from any country will considered 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 provide a country code. You can
do this during instaniation via the option `country_code`, or afterwards by
using `setCountryCode()`.
```php
$validator = new Zend\Validator\Iban(['country_code' => 'AT']);
if ($validator->isValid('AT611904300234573201')) {
// IBAN appears to be valid
} else {
// IBAN is not valid
}
```

View File

@@ -0,0 +1,239 @@
# Identical Validator
`Zend\Validator\Identical` allows you to validate if a given value is identical
with a set token.
## Supported options
The following options are supported for `Zend\Validator\Identical`:
- `strict`: Defines if the validation should be strict (i.e., if types should
also be considered). The default value is `true`.
- `token`: Sets the token against which the input will be validated.
- `literal`: If set to `true`, the validation will skip the lookup for elements
in the form context, and validate the token just the way it was provided. The
default value is `false`.
## Basic usage
To validate if two values are identical, you need to set the original value as
the token, as demonstrated in the following example:
token.
```php
$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 token after instantiation by using the method `setToken()`.
## Identical objects
`Zend\Validator\Identical` can validate not only strings, but any other variable
type, such as booleans, integers, floats, arrays, or even objects. As already
noted, the token and value must be identical.
```php
$valid = new Zend\Validator\Identical(123);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
> ### Type comparison
>
> You should be aware of the variable type used for validation. This means that
> the string `'3'` is not identical to integer `3`. When you want non-strict
> validation, you must set the `strict` option to `false`.
## Form elements
`Zend\Validator\Identical` supports the comparison of form elements. This can be
done by using the element's name as the `token`:
```php
$form->add([
'name' => 'elementOne',
'type' => 'Password',
]);
$form->add([
'name' => 'elementTwo',
'type' => 'Password',
'validators' => array(
[
'name' => 'Identical',
'options' => [
'token' => 'elementOne',
],
],
],
]);
```
By using the element's name from the first element as the `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
a validation error.
### Validating a Value From a Fieldset
Sometimes you will need to validate an input that lives inside a fieldset, and
this can be accomplished as follows:
```php
use Zend\Form\Element;
use Zend\Form\Fieldset;
use Zend\Form\Form;
use Zend\InputFilter\Input;
use Zend\InputFilter\InputFilter;
$userFieldset = new Fieldset('user'); // (1)
$userFieldset->add([
'name' => 'email', // (2)
'type' => 'Email',
]);
// Let's add one fieldset inside the 'user' fieldset,
// so we can see how to manage the token in a different deepness
$deeperFieldset = new Fieldset('deeperFieldset'); // (3)
$deeperFieldset->add([
'name' => 'deeperFieldsetInput', // (4)
'type' => 'Text',
'options' => [
'label' => 'What validator are we testing?',
],
]);
$userFieldset->add($deeperFieldset);
$signUpForm = new Form('signUp');
$signUpForm->add($userFieldset);
// Add an input that will validate the 'email' input from 'user' fieldset
$signUpForm->add([
'name' => 'confirmEmail', // (5)
'type' => 'Email',
]);
// Add an input that will validate the 'deeperFieldsetInput' from
// 'deeperFieldset' that lives inside the 'user' fieldset
$signUpForm->add([
'name' => 'confirmTestingValidator', // (6)
'type' => 'Text',
]);
// This will ensure the user enter the same email in 'email' (2) and
// 'confirmEmail' (5)
$inputFilter = new InputFilter();
$inputFilter->add([
'name' => 'confirmEmail', // references (5)
'validators' => [
array(
'name' => 'Identical',
'options' => [
// 'user' key references 'user' fieldset (1), and 'email'
// references 'email' element inside 'user' fieldset (2)
'token' => ['user' => 'email'],
],
],
],
]);
// This will ensure the user enter the same string in 'deeperFieldsetInput' (4)
// and 'confirmTestingValidator' (6)
$inputFilter->add([
'name' => 'confirmTestingValidator', // references (6)
'validators' => [
[
'name' => 'Identical',
'options' => [
'token' => [
'user' => [ // references 'user' fieldset (1)
// 'deeperFieldset' key references 'deeperFieldset'
// fieldset (3); 'deeperFieldsetInput' references
// 'deeperFieldsetInput' element (4)
'deeperFieldset' => 'deeperFieldsetInput',
],
],
],
],
],
]);
$signUpForm->setInputFilter($inputFilter);
```
> #### Use one token per leaf
>
> Aways make sure that your token array have just one key per level all the way
> till the leaf, otherwise you can end up with unexpected results.
## Strict validation
As mentioned before, `Zend\Validator\Identical` validates tokens using strict
typing. You can change this behaviour by using the `strict` option. The default
value for this property is `true`.
```php
$valid = new Zend\Validator\Identical(['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, `Zend\Validator\Identical` also supports the usage of
configuration settings during instantiation. This means that you can configure
this validator with a `Traversable` object.
There is a case which you should be aware of. If you are using an array as
token, and it contains a `token` key, you should wrap it within another
`token` key. See the examples below to undestand this situation.
```php
// This will not validate ['token' => 123], it will actually validate the
// integer 123
$valid = new Zend\Validator\Identical(['token' => 123]);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
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 you are using an array as the token, and it contains one element with a
`token` key, then you have to wrap it as shown in the example below:
```php
// Unlike the previous example, this will validate ['token' => 123]
$valid = new Zend\Validator\Identical(['token' => ['token' => 123]]);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
If the array you are willing to validate does not have a `token` key, you do not
need to wrap it.

View File

@@ -0,0 +1,161 @@
# InArray Validator
`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
The following options are supported for `Zend\Validator\InArray`:
- `haystack`: Sets the haystack for the validation. `recursive`: Defines if the
- validation should be done recursively. 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, but not type.
- `InArray::COMPARE_NOT_STRICT_AND_PREVENT_STR_TO_INT_VULNERABILTY`: This
operates in essentially the same way as `InArray::COMPARE_NOT_STRICT`,
but ensures that strings are not cast to integer during comparison,
preventing `0 == 'foo43'` types of false positives.
> ### Use non-strict carefully
>
> Non-strict mode (`InArray::COMPARE_NOT_STRICT`) 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`.
## Array validation
Basic usage is to provide an array during instantiation:
```php
$validator = new Zend\Validator\InArray([
'haystack' => ['value1', 'value2',...'valueN']
]);
if ($validator->isValid('value')) {
// value found
} else {
// no value found
}
```
This will behave exactly like PHP's `in_array()` method when passed only a
needle and haystack.
> ### Non-strict by default
>
> By default, this validation is not strict, nor can it validate
> multidimensional arrays.
Alternately, you can define the array to validate against after object
construction by using the `setHaystack()` method. `getHaystack()` returns the
actual set haystack array.
```php
$validator = new Zend\Validator\InArray();
$validator->setHaystack(['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 add 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`.
```php
// defaults to InArray::COMPARE_NOT_STRICT_AND_PREVENT_STR_TO_INT_VULNERABILITY
$validator = new Zend\Validator\InArray([
'haystack' => array('value1', 'value2', /* ... */ 'valueN'),
]);
// set strict mode
$validator = new Zend\Validator\InArray([
'haystack' => ['value1', 'value2', /* ... */ 'valueN'],
'strict' => InArray::COMPARE_STRICT, // equates to ``true``
]);
// set non-strict mode
$validator = new Zend\Validator\InArray([
'haystack' => ['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);
```
> ### Non-strict safe-mode by default
>
> 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.
```php
$validator = new Zend\Validator\InArray([
'haystack' => array(
'firstDimension' => ['value1', 'value2', / ... */ 'valueN'],
'secondDimension' => ['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.
```php
$validator = new Zend\Validator\InArray([
'firstDimension' => ['value1', 'value2', /* ... */ 'valueN'],
'secondDimension' => ['foo1', 'foo2', /* ... */ 'fooN'],
]);
$validator->setRecursive(true);
if ($validator->isValid('value')) {
// value found
} else {
// no value found
}
```
> ### Default setting for recursion
>
> By default, the recursive validation is turned off.
> ### 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.

View File

@@ -0,0 +1,66 @@
# Ip Validator
`Zend\Validator\Ip` allows you to validate if a given value is an IP address. It
supports the IPv4, IPv6, and IPvFuture definitions.
## Supported options
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
```php
$validator = new Zend\Validator\Ip();
if ($validator->isValid($ip)) {
// ip appears to be valid
} else {
// ip is invalid; print the reasons
}
```
> ### 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 not valid IP
> addresses. They are either hostnames or valid URLs but not IP addresses.
> ### IPv6/IPvFuture validation
>
> `Zend\Validator\Ip` validates IPv6/IPvFuture addresses using a 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; e.g., 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.
```php
$validator = new Zend\Validator\Ip(['allowipv6' => false]);
if ($validator->isValid($ip)) {
// ip appears to be valid ipv4 address
} else {
// ip is not an ipv4 address
}
```
> ### Default behaviour
>
> The default behaviour which `Zend\Validator\Ip` follows is to allow both
> standards.

View File

@@ -0,0 +1,86 @@
# Isbn Validator
`Zend\Validator\Isbn` allows you to validate an ISBN-10 or ISBN-13 value.
## Supported options
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 ISBN types. It defaults to
`Zend\Validator\Isbn::AUTO`. For details, take a look at the section on
[explicit types](#setting-an-explicit-isbn-validation-type).
## Basic usage
A basic example of usage is below:
```php
$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 follows:
```php
use Zend\Validator\Isbn;
$validator = new Isbn();
$validator->setType(Isbn::ISBN13);
// OR
$validator = new Isbn([ 'type' => 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:
```php
$validator = new Zend\Validator\Isbn();
$validator->setSeparator('-');
// OR
$validator = new Zend\Validator\Isbn(['separator' => '-']);
if ($validator->isValid($isbn)) {
// this is a valid ISBN with separator
} else {
// this is an invalid ISBN with separator
}
```
> ### Values without separators
>
> 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)

View File

@@ -0,0 +1,43 @@
# IsInstanceOf Validator
`Zend\Validator\IsInstanceOf` allows you to validate whether a given object is
an instance of a specific class or interface.
## Supported options
The following options are supported for `Zend\Validator\IsInstanceOf`:
- `className`: Defines the fully-qualified class name which objects must be an
instance of.
## Basic usage
```php
$validator = new Zend\Validator\IsInstanceOf([
'className' => 'Zend\Validator\Digits'
]);
$object = new Zend\Validator\Digits();
if ($validator->isValid($object)) {
// $object is an instance of Zend\Validator\Digits
} else {
// false. You can use $validator->getMessages() to retrieve error messages
}
```
If a string argument is passed to the constructor of
`Zend\Validator\IsInstanceOf`, then that value will be used as the class name:
```php
use Zend\Validator\Digits;
use Zend\Validator\IsInstanceOf;
$validator = new IsInstanceOf(Digits::class);
$object = new Digits();
if ($validator->isValid($object)) {
// $object is an instance of Zend\Validator\Digits
} else {
// false. You can use $validator->getMessages() to retrieve error messages
}
```

View File

@@ -0,0 +1,48 @@
# LessThan Validator
`Zend\Validator\LessThan` allows you to validate if a given value is less than a
maximum value.
> Supports only number validation
>
> `Zend\Validator\LessThan` supports only the validation of numbers. Strings or
> dates can not be validated with this validator.
## Supported options
The following options are supported for `Zend\Validator\LessThan`:
- `inclusive`: Defines if the validation is inclusive the maximum value or
exclusive. It defaults to `false`.
- `max`: Sets the maximum allowed value.
## Basic usage
To validate if a given value is less than a defined maximum:
```php
$valid = new Zend\Validator\LessThan(['max' => 10]);
$value = 12;
$return = $valid->isValid($value);
// returns false
```
The above example returns `true` for all values lower than 10.
## Inclusive validation
Sometimes it is useful to validate a value by including the maximum value:
```php
$valid = new Zend\Validator\LessThan([
'max' => 10,
'inclusive' => true,
]);
$value = 10;
$result = $valid->isValid($value);
// returns true
```
The example is identical to our first example, with the exception that we've
specified that the maximum is inclusive. Now the value '10' is allowed and will
return `true`.

View File

@@ -0,0 +1,80 @@
# NotEmpty Validator
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
The following options are supported for `Zend\Validator\NotEmpty`:
- `type`: Sets the type of validation which will be processed; for details, see
the section on [specifying empty behavior](#specifying-empty-behavior).
## Default behaviour
By default, this validator works differently than you would expect when you've
worked with PHP's `empty()` operator. In particular, this validator will
evaluate both the integer `0` and string `'0'` as empty.
```php
$valid = new Zend\Validator\NotEmpty();
$value = '';
$result = $valid->isValid($value);
// returns false
```
## Specifying empty behavior
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. By default,
this validation is not activate and returns `true` for any integer values.
- `float`: Returns `false` when a float `0.0` value is given. By default, this
validation is not activate 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 a `null` value is given.
- `php`: Returns `false` on wherever PHP's `empty()` would return `true`.
- `space`: Returns `false` when an string is given which contains only
whitespace.
- `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 its
`__toString()` method returns an empty string.
- `object_count`: Returns `false` when an object is given, it implements
`Countable`, and its 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 provide an array, you can use
constants, or you can provide a textual string. See the following examples:
```php
use Zend\Validator\NotEmpty;
// Returns false on 0
$validator = new NotEmpty(NotEmpty::INTEGER);
// Returns false on 0 or '0'
$validator = new NotEmpty( NotEmpty::INTEGER + NotEmpty::ZERO);
// Returns false on 0 or '0'
$validator = new NotEmpty([ NotEmpty::INTEGER, NotEmpty::ZERO ]);
// Returns false on 0 or '0'
$validator = new NotEmpty(['integer', 'zero']);
```
You can also provide an instance of `Traversable` to set the desired types. To
set types after instantiation, use the `setType()` method.

View File

@@ -0,0 +1,90 @@
# PostCode Validator
`Zend\I18n\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\I18n\Validator\PostCode` knows more than 160 different postal code
formats. To select the correct format there are two ways. You can either use a
fully qualified locale, or you can set your own format manually.
## Supported options
The following options are supported for `Zend\I18n\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.
## Usage
Using a locale is more convenient as zend-validator 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\I18n\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).
```php
$validator = new Zend\I18n\Validator\PostCode('de_AT');
```
When you don't set a locale yourself, then `Zend\I18n\Validator\PostCode` will
use the application wide set locale, or, when there is none, the locale returned
by `Locale`.
```php
// application wide locale within your bootstrap
Locale::setDefault('de_AT');
$validator = new Zend\I18n\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()`.
```php
$validator = new Zend\I18n\Validator\PostCode('de_AT');
$validator->setLocale('en_GB');
```
Postal code formats are 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()`.
```php
$validator = new Zend\I18n\Validator\PostCode('de_AT');
$validator->setFormat('AT-\d{5}');
```
> ### Conventions for self defined formats
>
> When using self defined formats, you should omit the regex delimiters and
> anchors (`'/^'` and `'$/'`). 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 its most basic, you may pass a string representing a fully qualified locale
to the constructor of `Zend\I18n\Validator\PostCode`.
```php
$validator = new Zend\I18n\Validator\PostCode('de_AT');
$validator = new Zend\I18n\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.
```php
$validator = new Zend\I18n\Validator\PostCode([
'locale' => 'de_AT',
'format' => 'AT_\d+'
]);
```

View File

@@ -0,0 +1,41 @@
# Regex Validator
This validator allows you to validate if a given string conforms a defined
regular expression.
## Supported options
The following options are supported for `Zend\Validator\Regex`:
- `pattern`: Sets the regular expression pattern for this validator.
## Usage
Validation with regular expressions allows complex validations
without writing a custom validator.
```php
$validator = new Zend\Validator\Regex(['pattern' => '/^Test/']);
$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns true
$validator->isValid("Pest"); // returns false
```
The pattern uses the same syntax as `preg_match()`. For details about regular
expressions take a look into [PHP's manual about PCRE pattern
syntax](http://php.net/reference.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()`.
```php
$validator = new Zend\Validator\Regex(['pattern' => '/^Test/']);
$validator->setPattern('ing$/');
$validator->isValid("Test"); // returns false
$validator->isValid("Testing"); // returns true
$validator->isValid("Pest"); // returns false
```

View File

@@ -0,0 +1,70 @@
# Sitemap Validators
The following validators conform to the
[Sitemap XML protocol](http://www.sitemaps.org/protocol.php).
## Supported options
There are no additional supported options for any of the `Sitemap` validators.
## Changefreq
`Zend\Validator\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
`Zend\Validator\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.
```php
$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
```
## Loc
`Zend\Validator\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()](https://zendframework.github.io/zend-uri/usage/#validating-the-uri)
internally.
## Priority
`Zend\Validator\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.
```php
$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
```

View File

@@ -0,0 +1,41 @@
# Step Validator
`Zend\Validator\Step` allows you to validate if a given value is a valid step
value. This validator requires the value to be a numeric value (either string,
int or float).
## Supported options
The following options are supported for `Zend\Validator\Step`:
- `baseValue`: This is the base value from which the step should be computed.
This option defaults to `0`
- `step`: This is the step value. This option defaults to `1`
## Basic usage
```php
$validator = new Zend\Validator\Step();
if ($validator->isValid(1)) {
// value is a valid step value
} else {
// false
}
```
## Using floating-point values
The `Step` validator also supports floating-point base and step values:
```php
$validator = new Zend\Validator\Step([
'baseValue' => 1.1,
'step' => 2.2,
]);
echo $validator->isValid(1.1); // prints true
echo $validator->isValid(3.3); // prints true
echo $validator->isValid(3.35); // prints false
echo $validator->isValid(2.2); // prints false
```

View File

@@ -0,0 +1,118 @@
# StringLength Validator
This validator allows you to validate if a given string is between a defined
length.
> Supports only string validation
>
> `Zend\Validator\StringLength` supports only the validation of strings.
> Integers, floats, dates or objects can not be validated with this validator.
## Supported options
The following options are supported for `Zend\Validator\StringLength`:
- `encoding`: Sets the `ICONV` encoding to use with the string.
- `min`: Sets the minimum allowed length for a string.
- `max`: Sets the maximum allowed length for a string.
## Default behaviour
By default, this validator checks if a value is between `min` and `max` using a
default`min` value of `0` and default `max` value of `NULL` (meaning unlimited).
As such, without any options, the validator only checks that the input is a
string.
## Limiting the maximum string length
To limit the maximum allowed length of a string you need to set the `max`
property. It accepts an integer value as input.
```php
$validator = new Zend\Validator\StringLength(['max' => 6]);
$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns false
```
You can set the maximum allowed length after instantiation by using the
`setMax()` method; `getMax()` retrieves the value.
```php
$validator = new Zend\Validator\StringLength();
$validator->setMax(6);
$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns false
```
## Limiting the minimum string length
To limit the minimal required string length, set the `min`
property using an integer value:
```php
$validator = new Zend\Validator\StringLength(['min' => 5]);
$validator->isValid("Test"); // returns false
$validator->isValid("Testing"); // returns true
```
You can set the value after instantiation using the `setMin()`
method; `getMin()` retrieves the value.
```php
$validator = new Zend\Validator\StringLength();
$validator->setMin(5);
$validator->isValid("Test"); // returns false
$validator->isValid("Testing"); // returns true
```
## Limiting both minimum and maximum string length
Sometimes you will need to set both a minimum and a maximum string length;
as an example, in a username input, you may want to limit the name to a maximum
of 30 characters, but require at least three charcters:
```php
$validator = new Zend\Validator\StringLength(['min' => 3, 'max' => 30]);
$validator->isValid("."); // returns false
$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns true
```
> ### Setting a maximum lower than the minimum
>
> When you try to set a lower maximum value than the specified minimum value, or
> a higher minimum value as the actual maximum value, the validator will raise
> an exception.
## Encoding of values
Strings are always using a encoding. Even when you don't set the encoding
explicitly, PHP uses one. When your application is using a different encoding
than PHP itself, you should set an encoding manually.
You can set an encoding at instantiation 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.
```php
$validator = new Zend\Validator\StringLength(['min' => 6]);
$validator->isValid("Ärger"); // returns false
$validator->setEncoding("UTF-8");
$validator->isValid("Ärger"); // returns true
$validator2 = new Zend\Validator\StringLength([
'min' => 6,
'encoding' => 'UTF-8',
]);
$validator2->isValid("Ärger"); // returns true
```
When your installation and your application are using different encodings, then
you should always set an encoding manually.

View File

@@ -0,0 +1,37 @@
# Timezone Validator
`Zend\Validator\Timezone` allows validating if an input string represents a
timezone.
## Supported validation types
The `Zend\Validator\Timezone` validator is capable of validating the
abbreviation (e.g. `ewt`) as well as the location string (e.g.
`America/Los_Angeles`). These options are stored in the validator as
`LOCATION`, `ABBREVIATION`, and `ALL` class constants.
## Basic Usage
The default validation type will check against abbreviations as well as the
location string.
```php
$validator = new Zend\Validator\Timezone();
$validator->isValid('America/Los_Angeles'); // returns true
$validator->isValid('ewt'); // returns true
$validator->isValid('Foobar'); // returns false
```
To validate against only the location string you can set the type:
```php
use Zend\Validator\Timezone;
$validator = new Timezone();
$validator->setType(Timezone::LOCATION);
$validator->isValid('America/Los_Angeles'); // returns true
$validator->isValid('ewt'); // returns false
$validator->isValid('Foobar'); // returns false
```

View File

@@ -0,0 +1,30 @@
# Uri Validator
`Zend\Validator\Uri` allows you to validate a URI using the `Zend\Uri\Uri`
handler to parse the URI. The validator allows for both validation of absolute
and/or relative URIs. There is the possibility to exchange the handler for
another one in case the parsing of the uri should be done differently.
## Supported options
The following options are supported for `Zend\Validator\Uri`:
- `uriHandler`: Defines the handler to be used to parse the uri. This options
defaults to a new instance of `Zend\Uri\Uri`.
- `allowRelative`: Defines if relative paths are allowed. This option defaults
to `true`.
- `allowAbsolute`: Defines if absolute paths are allowed. This option defaults
to `true`.
## Basic usage
```php
$validator = new Zend\Validator\Uri();
$uri = 'http://framework.zend.com/manual';
if ($validator->isValid($uri)) {
// $uri was valid
} else {
// false. You can use $validator->getMessages() to retrieve error messages
}
```

View File

@@ -0,0 +1,38 @@
# UUID Validator
`Zend\Validator\Uuid` allows validating [Universally Unique IDentifiers](https://en.wikipedia.org/wiki/Universally_unique_identifier)
(UUIDs). UUIDs are 128-bit values that are guaranteed to be "practically unique"
in order to help prevent identifier conflicts. Five separate UUID versions
exist:
- Version 1, which uses a combination of date-time and hardware MAC addresses to
generate the hash.
- Version 2, which uses a combination of date-time and system user/group identifiers.
- Version 3, which uses an MD5sum of a URI or distinguished name to generate the
hash.
- Version 4, which uses a CSPRNG to generate the hash.
- Version 5, which uses the same idea as Version 3, but using SHA-1 for hashing.
The `Uuid` validator is capable of validating whether a string is a valid UUID
of any version. It does not validate that the UUID exists in your system,
however, only that it is well-formed.
> ### Introduced in 2.8.0
>
> `Zend\Validator\Uuid` was introduced with version 2.8.0.
## Supported options
The `Uuid` validator has no additional options.
## Basic usage
```php
$validator = new Zend\Validator\Uuid();
if ($validator->isValid($uuid)) {
// UUID was valid
} else {
// Invalid/mal-formed UUID; use $validator->getMessages() for more detail
}
```

View File

@@ -0,0 +1,222 @@
# Writing Validators
zend-validator supplies a set of commonly needed validators, but many
applications have needs for custom validators. The component allows this via
implementations of `Zend\Validator\ValidatorInterface`.
`Zend\Validator\ValidatorInterface` defines two methods: `isValid()` and
`getMessages()`. An object that implements the interface may be added to a
validator chain using `Zend\Validator\ValidatorChain::addValidator()`. Such
objects may also be used with
[zend-inputfilter](https://zendframework.github.io/zend-inputfilter).
Validators will return a boolean value from `isValid()`, and report information
regarding **why** a value failed validation via `getMessages()`. The
availability of the reasons for validation failures may be valuable to an
application for various purposes, such as providing statistics for usability
analysis.
Basic validation failure message functionality is implemented in
`Zend\Validator\AbstractValidator`, which you may extend for your custom
validators. Extending class you would implement the `isValid()` method logic
and define the message variables and message templates that correspond to the
types of validation failures that can occur. If a value fails your validation
tests, then `isValid()` should return `false`. If the value passes your
validation tests, then `isValid()` should return `true`.
In general, the `isValid()` method should not throw any exceptions, except where
it is impossible to determine whether or not the input value is valid. A few
examples of reasonable cases for throwing an exception might be if a file cannot
be opened, an LDAP server could not be contacted, or a database connection is
unavailable, where such a thing may be required for validation success or
failure to be determined.
## Creating a Validation Class
The following example demonstrates how a custom validator might be written. In
this case, the validator tests that a value is a floating point value.
```php
namespace MyValid;
use Zend\Validator\AbstractValidator;
class Float extends AbstractValidator
{
const FLOAT = 'float';
protected $messageTemplates = [
self::FLOAT => "'%value%' is not a floating point value",
];
public function isValid($value)
{
$this->setValue($value);
if (! is_float($value)) {
$this->error(self::FLOAT);
return false;
}
return true;
}
}
```
The class defines a template for its single validation failure message, which
includes the built-in magic parameter, `%value%`. The call to `setValue()`
prepares the object to insert the tested value into the failure message
automatically, should the value fail validation. The call to `error()` tracks a
reason for validation failure. Since this class only defines one failure
message, it is not necessary to provide `error()` with the name of the failure
message template.
## Writing a Validation Class having Dependent Conditions
The following example demonstrates a more complex set of validation rules:
- The input must be numeric.
- The input must fall within a range of bouncary values.
An input value would fail validation for exactly one of the following reasons:
- The input value is not numeric.
- The input value is less than the minimum allowed value.
- The input value is more than the maximum allowed value.
These validation failure reasons are then translated to definitions in the
class:
```php
namespace MyValid;
use Zend\Validator\AbstractValidator;
class NumericBetween extends AbstractValidator
{
const MSG_NUMERIC = 'msgNumeric';
const MSG_MINIMUM = 'msgMinimum';
const MSG_MAXIMUM = 'msgMaximum';
public $minimum = 0;
public $maximum = 100;
protected $messageVariables = [
'min' => 'minimum',
'max' => 'maximum',
];
protected $messageTemplates = [
self::MSG_NUMERIC => "'%value%' is not numeric",
self::MSG_MINIMUM => "'%value%' must be at least '%min%'",
self::MSG_MAXIMUM => "'%value%' must be no more than '%max%'",
];
public function isValid($value)
{
$this->setValue($value);
if (! is_numeric($value)) {
$this->error(self::MSG_NUMERIC);
return false;
}
if ($value < $this->minimum) {
$this->error(self::MSG_MINIMUM);
return false;
}
if ($value > $this->maximum) {
$this->error(self::MSG_MAXIMUM);
return false;
}
return true;
}
}
```
The public properties `$minimum` and `$maximum` have been established to provide
the minimum and maximum boundaries, respectively, for a value to successfully
validate. The class also defines two message variables that correspond to the
public properties and allow `min` and `max` to be used in message templates as
magic parameters, just as with `value`.
Note that if any one of the validation checks in `isValid()` fails, an
appropriate failure message is prepared, and the method immediately returns
`false`. These validation rules are therefore sequentially dependent; that is,
if one test should fail, there is no need to test any subsequent validation
rules. This need not be the case, however. The following example illustrates how
to write a class having independent validation rules, where the validation
object may return multiple reasons why a particular validation attempt failed.
## Validation with Independent Conditions, Multiple Reasons for Failure
Consider writing a validation class for password strength enforcement - when a
user is required to choose a password that meets certain criteria for helping
secure user accounts. Let us assume that the password security criteria enforce
that the password:
- is at least 8 characters in length,
- contains at least one uppercase letter,
- contains at least one lowercase letter,
- and contains at least one digit character.
The following class implements these validation criteria:
```php
namespace MyValid;
use Zend\Validator\AbstractValidator;
class PasswordStrength extends AbstractValidator
{
const LENGTH = 'length';
const UPPER = 'upper';
const LOWER = 'lower';
const DIGIT = 'digit';
protected $messageTemplates = [
self::LENGTH => "'%value%' must be at least 8 characters in length",
self::UPPER => "'%value%' must contain at least one uppercase letter",
self::LOWER => "'%value%' must contain at least one lowercase letter",
self::DIGIT => "'%value%' must contain at least one digit character",
];
public function isValid($value)
{
$this->setValue($value);
$isValid = true;
if (strlen($value) < 8) {
$this->error(self::LENGTH);
$isValid = false;
}
if (! preg_match('/[A-Z]/', $value)) {
$this->error(self::UPPER);
$isValid = false;
}
if (! preg_match('/[a-z]/', $value)) {
$this->error(self::LOWER);
$isValid = false;
}
if (! preg_match('/\d/', $value)) {
$this->error(self::DIGIT);
$isValid = false;
}
return $isValid;
}
}
```
Note that the four criteria tests in `isValid()` do not immediately return
`false`. This allows the validation class to provide **all** of the reasons that
the input password failed to meet the validation requirements. If, for example,
a user were to input the string `#$%` as a password, `isValid()` would cause
all four validation failure messages to be returned by a subsequent call to
`getMessages()`.