Compare commits

..

No commits in common. "master" and "v1.4.4" have entirely different histories.

45 changed files with 259 additions and 1329 deletions

1
.github/FUNDING.yml vendored
View File

@ -1 +0,0 @@
tidelift: "packagist/vlucas/valitron"

View File

@ -1,73 +0,0 @@
name: Run Tests
on: [push, pull_request]
jobs:
test:
runs-on: ${{ matrix.operating-system }}
strategy:
matrix:
operating-system: ['ubuntu-latest']
php-versions:
- '5.4'
- '5.5'
- '5.6'
- '7.0'
- '7.1'
- '7.2'
- '7.3'
- '7.4'
- '8.0'
# - '8.1'
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php-versions }}
- name: Cache composer packages
id: composer-cache
uses: actions/cache@v2
with:
path: vendor
key: ${{ runner.os }}-php-${{ matrix.php-versions }}-${{ hashFiles('**/composer.lock') }}
restore-keys: |
${{ runner.os }}-php-${{ matrix.php-versions }}-
- name: Validate composer configuration
run: |
composer validate
- name: Install dependencies
run: |
composer install --no-progress
- name: Run tests
run: |
composer run-script test
# test-hhvm:
# runs-on: ubuntu-latest
# steps:
# - name: Checkout
# uses: actions/checkout@v2
# - name: Setup HHVM
# uses: azjezz/setup-hhvm@v1
# with:
# version: latest
# debug: false
# - name: Cache composer packages
# id: composer-cache
# uses: actions/cache@v2
# with:
# path: vendor
# key: ${{ runner.os }}-hhvm-${{ hashFiles('**/composer.lock') }}
# restore-keys: |
# ${{ runner.os }}-hhvm-
# - name: Validate composer configuration
# run: |
# composer validate
# - name: Install dependencies
# run: |
# composer install --no-progress
# - name: Run tests
# run: |
# composer run-script test

1
.gitignore vendored
View File

@ -3,4 +3,3 @@ composer.phar
composer.lock composer.lock
vendor vendor
.idea/ .idea/
.phpunit.result.cache

27
.travis.yml Normal file
View File

@ -0,0 +1,27 @@
# see http://about.travis-ci.org/docs/user/languages/php/ for more hints
language: php
# list any PHP version you want to test against
php:
- 5.4
- 5.5
- 5.6
- 7.0
- 7.1
- 7.2
- nightly
- hhvm
matrix:
allow_failures:
- php: hhvm
- php: nightly
include:
- php: 5.3
dist: precise
before_script:
- composer install
# Script to run tests
script: composer test

246
README.md
View File

@ -6,12 +6,10 @@ methods with a focus on readable and concise syntax. Valitron is the
simple and pragmatic validation library you've been looking for. simple and pragmatic validation library you've been looking for.
[![Build [![Build
Status](https://github.com/vlucas/valitron/actions/workflows/test.yml/badge.svg)](https://github.com/vlucas/valitron/actions/workflows/test.yml) Status](https://travis-ci.org/vlucas/valitron.png?branch=master)](https://travis-ci.org/vlucas/valitron)
[![Latest Stable Version](https://poser.pugx.org/vlucas/valitron/v/stable.png)](https://packagist.org/packages/vlucas/valitron) [![Latest Stable Version](https://poser.pugx.org/vlucas/valitron/v/stable.png)](https://packagist.org/packages/vlucas/valitron)
[![Total Downloads](https://poser.pugx.org/vlucas/valitron/downloads.png)](https://packagist.org/packages/vlucas/valitron) [![Total Downloads](https://poser.pugx.org/vlucas/valitron/downloads.png)](https://packagist.org/packages/vlucas/valitron)
[Get supported vlucas/valitron with the Tidelift Subscription](https://tidelift.com/subscription/pkg/packagist-vlucas-valitron?utm_source=packagist-vlucas-valitron&utm_medium=referral&utm_campaign=readme)
## Why Valitron? ## Why Valitron?
Valitron was created out of frustration with other validation libraries Valitron was created out of frustration with other validation libraries
@ -127,63 +125,11 @@ V::lang('ar');
``` ```
Disabling the {field} name in the output of the error message.
```php
use Valitron\Validator as V;
$v = new Valitron\Validator(['name' => 'John']);
$v->rule('required', ['name']);
// Disable prepending the labels
$v->setPrependLabels(false);
// Error output for the "false" condition
[
["name"] => [
"is required"
]
]
// Error output for the default (true) condition
[
["name"] => [
"name is required"
]
]
```
You can conditionally require values using required conditional rules. In this example, for authentication, we're requiring either a token when both the email and password are not present, or a password when the email address is present.
```php
// this rule set would work for either data set...
$data = ['email' => 'test@test.com', 'password' => 'mypassword'];
// or...
$data = ['token' => 'jashdjahs83rufh89y38h38h'];
$v = new Valitron\Validator($data);
$v->rules([
'requiredWithout' => [
['token', ['email', 'password'], true]
],
'requiredWith' => [
['password', ['email']]
],
'email' => [
['email']
]
'optional' => [
['email']
]
]);
$this->assertTrue($v->validate());
```
## Built-in Validation Rules ## Built-in Validation Rules
* `required` - Field is required * `required` - Field is required
* `requiredWith` - Field is required if any other fields are present
* `requiredWithout` - Field is required if any other fields are NOT present
* `equals` - Field must match another field (email/password confirmation) * `equals` - Field must match another field (email/password confirmation)
* `different` - Field must be different than another field * `different` - Field must be different than another field
* `accepted` - Checkbox or Radio must be accepted (yes, on, 1, true) * `accepted` - Checkbox or Radio must be accepted (yes, on, 1, true)
@ -197,7 +143,6 @@ $this->assertTrue($v->validate());
* `lengthMax` - String must be less than given length * `lengthMax` - String must be less than given length
* `min` - Minimum * `min` - Minimum
* `max` - Maximum * `max` - Maximum
* `listContains` - Performs in_array check on given array values (the other way round than `in`)
* `in` - Performs in_array check on given array values * `in` - Performs in_array check on given array values
* `notIn` - Negation of `in` rule (not in array of values) * `notIn` - Negation of `in` rule (not in array of values)
* `ip` - Valid IP address * `ip` - Valid IP address
@ -222,7 +167,6 @@ $this->assertTrue($v->validate());
* `creditCard` - Field is a valid credit card number * `creditCard` - Field is a valid credit card number
* `instanceOf` - Field contains an instance of the given class * `instanceOf` - Field contains an instance of the given class
* `optional` - Value does not need to be included in data array. If it is however, it must pass validation. * `optional` - Value does not need to be included in data array. If it is however, it must pass validation.
* `arrayHasKeys` - Field is an array and contains all specified keys.
**NOTE**: If you are comparing floating-point numbers with min/max validators, you **NOTE**: If you are comparing floating-point numbers with min/max validators, you
should install the [BCMath](http://us3.php.net/manual/en/book.bc.php) should install the [BCMath](http://us3.php.net/manual/en/book.bc.php)
@ -254,133 +198,7 @@ $v->rules([
$v->validate(); $v->validate();
``` ```
## requiredWith fields usage Example using alternate syntax.
The `requiredWith` rule checks that the field is required, not null, and not the empty string, if any other fields are present, not null, and not the empty string.
```php
// password field will be required when the username field is provided and not empty
$v->rule('requiredWith', 'password', 'username');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'spiderman', 'password' => 'Gr33nG0Blin']);
$v->rules([
'requiredWith' => [
['password', 'username']
]
]);
$v->validate();
```
*Note* You can provide multiple values as an array. In this case if ANY of the fields are present the field will be required.
```php
// in this case the password field will be required if the username or email fields are present
$v->rule('requiredWith', 'password', ['username', 'email']);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'spiderman', 'password' => 'Gr33nG0Blin']);
$v->rules([
'requiredWith' => [
['password', ['username', 'email']]
]
]);
$v->validate();
```
### Strict flag
The strict flag will change the `requiredWith` rule to `requiredWithAll` which will require the field only if ALL of the other fields are present, not null, and not the empty string.
```php
// in this example the suffix field is required only when both the first_name and last_name are provided
$v->rule('requiredWith', 'suffix', ['first_name', 'last_name'], true);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['first_name' => 'steve', 'last_name' => 'holt', 'suffix' => 'Mr']);
$v->rules([
'requiredWith' => [
['suffix', ['first_name', 'last_name'], true]
]
]);
$v->validate();
```
Likewise, in this case `validate()` would still return true, as the suffix field would not be required in strict mode, as not all of the fields are provided.
```php
$v = new Valitron\Validator(['first_name' => 'steve']);
$v->rules([
'requiredWith' => [
['suffix', ['first_name', 'last_name'], true]
]
]);
$v->validate();
```
## requiredWithout fields usage
The `requiredWithout` rule checks that the field is required, not null, and not the empty string, if any other fields are NOT present.
```php
// this rule will require the username field when the first_name is not present
$v->rule('requiredWithout', 'username', 'first_name')
```
Alternate syntax.
```php
// this will return true, as the username is provided when the first_name is not provided
$v = new Valitron\Validator(['username' => 'spiderman']);
$v->rules([
'requiredWithout' => [
['username', 'first_name']
]
]);
$v->validate();
```
*Note* You can provide multiple values as an array. In this case if ANY of the fields are NOT present the field will be required.
```php
// in this case the username field will be required if either the first_name or last_name fields are not present
$v->rule('requiredWithout', 'username', ['first_name', 'last_name']);
```
Alternate syntax.
```php
// this passes validation because although the last_name field is not present, the username is provided
$v = new Valitron\Validator(['username' => 'spiderman', 'first_name' => 'Peter']);
$v->rules([
'requiredWithout' => [
['username', ['first_name', 'last_name']]
]
]);
$v->validate();
```
### Strict flag
The strict flag will change the `requiredWithout` rule to `requiredWithoutAll` which will require the field only if ALL of the other fields are not present.
```php
// in this example the username field is required only when both the first_name and last_name are not provided
$v->rule('requiredWithout', 'username', ['first_name', 'last_name'], true);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'BatMan']);
$v->rules([
'requiredWithout' => [
['username', ['first_name', 'last_name'], true]
]
]);
$v->validate();
```
Likewise, in this case `validate()` would still return true, as the username field would not be required in strict mode, as all of the fields are provided.
```php
$v = new Valitron\Validator(['first_name' => 'steve', 'last_name' => 'holt']);
$v->rules([
'requiredWithout' => [
['suffix', ['first_name', 'last_name'], true]
]
]);
$v->validate();
```
## equals fields usage ## equals fields usage
The `equals` rule checks if two fields are equals in the data array, and that the second field is not null. The `equals` rule checks if two fields are equals in the data array, and that the second field is not null.
@ -467,19 +285,24 @@ $v->rules([
$v->validate(); $v->validate();
``` ```
*Note* the optional boolean flag for strict mode makes sure integers are to be supplied in a strictly numeric form. So the following rule would evaluate to true: *Note* the optional boolean flag for strict mode will allow for integers to be supplied as negative values. So the following rule would evaluate to true:
```php ```php
$v = new Valitron\Validator(['negative' => '-27', 'positive'=>'27']); $v = new Valitron\Validator(['age' => '-27']);
$v->rule('integer', 'age', true); $v->rules([
$v->rule('integer', 'height', true); 'integer' => [
['age', true]
]
]);
$v->validate(); $v->validate();
``` ```
Whereas the same for a positive (+) value would evaluate to false, as the + in this case is redundant:
Whereas the following will evaluate to false, as the + for the positive number in this case is redundant:
```php ```php
$v = new Valitron\Validator(['negative' => '-27', 'positive'=>'+27']); $v = new Valitron\Validator(['age' => '+27']);
$v->rule('integer', 'age', true); $v->rules([
$v->rule('integer', 'height', true); 'integer' => [
['age', true]
]
]);
$v->validate(); $v->validate();
``` ```
@ -619,23 +442,6 @@ $v->rules([
$v->validate(); $v->validate();
``` ```
## listContains fields usage
The `listContains` rule checks that the field is present in a given array of values.
```php
$v->rule('listContains', 'color', 'yellow');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['color' => ['blue', 'green', 'red', 'yellow']]);
$v->rules([
'listContains' => [
['color', 'yellow']
]
]);
$v->validate();
```
## in fields usage ## in fields usage
The `in` rule checks that the field is present in a given array of values. The `in` rule checks that the field is present in a given array of values.
```php ```php
@ -1132,23 +938,6 @@ $v->rules([
$v->validate(); $v->validate();
``` ```
## arrayHasKeys fields usage
The `arrayHasKeys` rule ensures that the field is an array and that it contains all the specified keys.
Returns false if the field is not an array or if no required keys are specified or if some key is missing.
```php
$v = new Valitron\Validator([
'address' => [
'name' => 'Jane Doe',
'street' => 'Doe Square',
'city' => 'Doe D.C.'
]
]);
$v->rule('arrayHasKeys', 'address', ['name', 'street', 'city']);
$v->validate();
```
## Adding Custom Validation Rules ## Adding Custom Validation Rules
To add your own validation rule, use the `addRule` method with a rule To add your own validation rule, use the `addRule` method with a rule
@ -1349,6 +1138,3 @@ before running the tests:
7. Create new Pull Request 7. Create new Pull Request
8. Pat yourself on the back for being so awesome 8. Pat yourself on the back for being so awesome
## Security Disclosures and Contact Information
To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure.

View File

@ -3,20 +3,20 @@
"type": "library", "type": "library",
"description": "Simple, elegant, stand-alone validation library with NO dependencies", "description": "Simple, elegant, stand-alone validation library with NO dependencies",
"keywords": ["validation", "validator", "valid"], "keywords": ["validation", "validator", "valid"],
"homepage": "https://github.com/vlucas/valitron", "homepage": "http://github.com/vlucas/valitron",
"license": "BSD-3-Clause", "license": "BSD-3-Clause",
"authors": [ "authors": [
{ {
"name": "Vance Lucas", "name": "Vance Lucas",
"email": "vance@vancelucas.com", "email": "vance@vancelucas.com",
"homepage": "https://www.vancelucas.com" "homepage": "http://www.vancelucas.com"
} }
], ],
"require": { "require": {
"php": ">=5.3.2" "php": ">=5.3.2"
}, },
"require-dev": { "require-dev": {
"phpunit/phpunit": ">=4.8.35" "phpunit/phpunit": "^4.8.35 || ^5.5 || ^6.5"
}, },
"suggest": { "suggest": {
"ext-mbstring": "It can support the multiple bytes string length." "ext-mbstring": "It can support the multiple bytes string length."

View File

@ -11,7 +11,6 @@ return array(
'min' => "يجب ان يكون اعلي من %s", 'min' => "يجب ان يكون اعلي من %s",
'max' => "يجب ان يكون اقل من %s", 'max' => "يجب ان يكون اقل من %s",
'in' => "الُمدخل يغير صحيح", 'in' => "الُمدخل يغير صحيح",
'listContains' => "الُمدخل يغير صحيح",
'notIn' => "الُمدخل يغير صحيح", 'notIn' => "الُمدخل يغير صحيح",
'ip' => "رقم الإتصال غير صحيح", 'ip' => "رقم الإتصال غير صحيح",
'email' => "البريد الألكتروني غير صحيح", 'email' => "البريد الألكتروني غير صحيح",

View File

@ -10,7 +10,6 @@ return array(
'length' => "%d qədər uzunluğu olmalıdır", 'length' => "%d qədər uzunluğu olmalıdır",
'min' => "minimum %s qədər olmalıdır", 'min' => "minimum %s qədər olmalıdır",
'max' => "maksimum %s qədər olmalıdır", 'max' => "maksimum %s qədər olmalıdır",
'listContains' => "yalnış dəyər ehtiva edir",
'in' => "yalnış dəyər ehtiva edir", 'in' => "yalnış dəyər ehtiva edir",
'notIn' => "yalnış dəyər ehtiva edir", 'notIn' => "yalnış dəyər ehtiva edir",
'ip' => "düzgün IP ünvanı deyil", 'ip' => "düzgün IP ünvanı deyil",

View File

@ -10,7 +10,6 @@ return array(
'length' => "трябва да бъде %d символа дълго", 'length' => "трябва да бъде %d символа дълго",
'min' => "трябвя да бъде поне %s", 'min' => "трябвя да бъде поне %s",
'max' => "трябва да бъде не повече от %s", 'max' => "трябва да бъде не повече от %s",
'listContains' => "съдържа невалидна стойност",
'in' => "съдържа невалидна стойност", 'in' => "съдържа невалидна стойност",
'notIn' => "съдържа невалидна стойност", 'notIn' => "съдържа невалидна стойност",
'ip' => "е невалиден IP адрес", 'ip' => "е невалиден IP адрес",

View File

@ -10,7 +10,6 @@ return array(
'length' => "kann nicht länger als %d sein", 'length' => "kann nicht länger als %d sein",
'min' => "muss größer als %s sein", 'min' => "muss größer als %s sein",
'max' => "muss kleiner als %s sein", 'max' => "muss kleiner als %s sein",
'listContains' => "enthält einen ungültigen Wert",
'in' => "enthält einen ungültigen Wert", 'in' => "enthält einen ungültigen Wert",
'notIn' => "enthält einen ungültigen Wert", 'notIn' => "enthält einen ungültigen Wert",
'ip' => "enthält keine gültige IP-Addresse", 'ip' => "enthält keine gültige IP-Addresse",

View File

@ -10,7 +10,6 @@ return array(
'length' => "πρέπει να είναι μεγαλύτερο από %d", 'length' => "πρέπει να είναι μεγαλύτερο από %d",
'min' => "πρέπει να είναι τουλάχιστον %s", 'min' => "πρέπει να είναι τουλάχιστον %s",
'max' => "δεν πρέπει να είναι περισσότερο από %s", 'max' => "δεν πρέπει να είναι περισσότερο από %s",
'listContains' => "περιέχει μη έγκυρη τιμή",
'in' => "περιέχει μη έγκυρη τιμή", 'in' => "περιέχει μη έγκυρη τιμή",
'notIn' => "περιέχει μη έγκυρη τιμή", 'notIn' => "περιέχει μη έγκυρη τιμή",
'ip' => "δεν είναι έγκυρη διεύθυνση IP", 'ip' => "δεν είναι έγκυρη διεύθυνση IP",

View File

@ -10,7 +10,6 @@ return array(
'length' => "must be %d characters long", 'length' => "must be %d characters long",
'min' => "must be at least %s", 'min' => "must be at least %s",
'max' => "must be no more than %s", 'max' => "must be no more than %s",
'listContains' => "contains invalid value",
'in' => "contains invalid value", 'in' => "contains invalid value",
'notIn' => "contains invalid value", 'notIn' => "contains invalid value",
'ip' => "is not a valid IP address", 'ip' => "is not a valid IP address",
@ -35,8 +34,5 @@ return array(
'lengthMax' => "must not exceed %d characters", 'lengthMax' => "must not exceed %d characters",
'instanceOf' => "must be an instance of '%s'", 'instanceOf' => "must be an instance of '%s'",
'containsUnique' => "must contain unique elements only", 'containsUnique' => "must contain unique elements only",
'requiredWith' => "is required",
'requiredWithout'=> "is required",
'subset' => "contains an item that is not in the list", 'subset' => "contains an item that is not in the list",
'arrayHasKeys' => "does not contain all required keys",
); );

View File

@ -30,8 +30,5 @@ return array(
'creditCard' => "debe ser un numero de tarjeta de crédito válido", 'creditCard' => "debe ser un numero de tarjeta de crédito válido",
"lengthMin" => "debe tener al menos %d caracteres", "lengthMin" => "debe tener al menos %d caracteres",
"lengthMax" => "debe tener menos de %d caracteres", "lengthMax" => "debe tener menos de %d caracteres",
"instanceOf" => "debe ser una instancia de '%s'", "instanceOf" => "debe ser una instancia de '%s'"
'containsUnique' => "debe contener solo valores únicos",
'subset' => "contiene un elemento que no está en la lista",
'arrayHasKeys' => "no contiene todas las claves requeridas"
); );

View File

@ -1,42 +0,0 @@
<?php
return array(
'required' => "الزامی است",
'equals' => " باید برابر باشد با '%s'",
'different' => "باید متفاوت باشد از '%s'",
'accepted' => "باید پذیرفته شده باشد",
'numeric' => "باید مقدار عددی باشد",
'integer' => "باید عددی طبیعی باشد",
'length' => "طول باید %d باشد",
'min' => "حداقل باید %s کاراکتر باشد",
'max' => "نباید بیشتر از %s کارکتر باشد",
'listContains' => "حاوی مقدار نامعتبر",
'in' => "حاوی مقدار نامعتبر",
'notIn' => "حاوی مقدار نامعتبر",
'ip' => " آدرس معتبر نیست IP",
'ipv4' => "آدرس معتبر نیست IPv4",
'ipv6' => "آدرس معتبر نیست IPv6",
'email' => "آدرس ایمیل معتبر نیست",
'url' => "معتبر نیست URL",
'urlActive' => "دامنه باید فعال باشد",
'alpha' => "باید حاوی حروف a-z باشد",
'alphaNum' => "باید حاوی حروف a-z و/یا اعداد 0-9 باشد",
'slug' => "باید حاوی حروف a-z, اعداد 0-9, دش و آندراسکور باشد",
'regex' => "حاوی کارکترهای نامعتبر",
'date' => "تاریخ معتبر نیست",
'dateFormat' => "فرمت تاریخ باید به این شکل '%s' باشد",
'dateBefore' => "تاریخ باید قبل از '%s' باشد",
'dateAfter' => "تاریخ باید بعد از '%s' باشد",
'contains' => "باید حاوی %s باشد",
'boolean' => "مقدار باید بولین باشد",
'lengthBetween' => "طول باید بین %d و %d کاراکتر باشد",
'creditCard' => "شماره کارت اعتباری معتبر نیست",
'lengthMin' => "طول باید حداقل %d کاراکتر باشد",
'lengthMax' => "طول نباید بیشتر از %d کاراکتر باشد",
'instanceOf' => "باید آبجکتی از نوع '%s' باشد",
'containsUnique' => "باید حاوی المان ها یونیک باشد",
'requiredWith' => "الزامی است",
'requiredWithout'=> "الزامی است",
'subset' => "حاوی آیتمی است که در لیست موجود نیست",
'arrayHasKeys' => "همه کلیدهای الزامی را ندارد",
);

View File

@ -10,7 +10,6 @@ return array(
'length' => "on lyhyempi kuin %d", 'length' => "on lyhyempi kuin %d",
'min' => "ei ole vähintään %s", 'min' => "ei ole vähintään %s",
'max' => "ei ole enintään %s", 'max' => "ei ole enintään %s",
'listContains' => "sisältää virheellisen arvon",
'in' => "sisältää virheellisen arvon", 'in' => "sisältää virheellisen arvon",
'notIn' => "sisältää virheellisen arvon", 'notIn' => "sisältää virheellisen arvon",
'ip' => "ei ole oikeanmuotoinen IP-osoite", 'ip' => "ei ole oikeanmuotoinen IP-osoite",

View File

@ -10,7 +10,6 @@ return array(
'length' => "doit être plus long que %d", 'length' => "doit être plus long que %d",
'min' => "doit être plus grand que %s", 'min' => "doit être plus grand que %s",
'max' => "doit être plus petit que %s", 'max' => "doit être plus petit que %s",
'listContains' => "contient une valeur non valide",
'in' => "contient une valeur non valide", 'in' => "contient une valeur non valide",
'notIn' => "contient une valeur non valide", 'notIn' => "contient une valeur non valide",
'ip' => "n'est pas une adresse IP valide", 'ip' => "n'est pas une adresse IP valide",
@ -31,10 +30,5 @@ return array(
'creditCard' => "doit être un numéro de carte de crédit valide", 'creditCard' => "doit être un numéro de carte de crédit valide",
'lengthMin' => "doit avoir au moins %d caractères", 'lengthMin' => "doit avoir au moins %d caractères",
'lengthMax' => "ne doit pas dépasser %d caractères", 'lengthMax' => "ne doit pas dépasser %d caractères",
'instanceOf' => "doit être une instance de '%s'", 'instanceOf' => "doit être une instance de '%s'"
"containsUnique" => "doit contenir des élements unique",
"requiredWith" => "est requis",
"requiredWithout" => "est requis",
"subset" => "contient un élement qui n'est pas dans la liste",
"arrayHasKeys" => "ne contient pas toutes les clés requises"
); );

View File

@ -10,7 +10,6 @@ return array(
'length' => "harus lebih panjang dari %d", 'length' => "harus lebih panjang dari %d",
'min' => "harus lebih besar dari %s", 'min' => "harus lebih besar dari %s",
'max' => "harus kurang dari %s", 'max' => "harus kurang dari %s",
'listContains' => "berisi nilai/value yang tidak valid",
'in' => "berisi nilai/value yang tidak valid", 'in' => "berisi nilai/value yang tidak valid",
'notIn' => "berisi nilai/value yang tidak valid", 'notIn' => "berisi nilai/value yang tidak valid",
'ip' => "format alamat IP tidak benar", 'ip' => "format alamat IP tidak benar",

View File

@ -10,7 +10,6 @@ return array(
'length' => "deve avere una lunghezza di %d", 'length' => "deve avere una lunghezza di %d",
'min' => "deve essere superiore a %s", 'min' => "deve essere superiore a %s",
'max' => "deve essere inferiore a %s", 'max' => "deve essere inferiore a %s",
'listContains' => "contiene un valore non valido",
'in' => "contiene un valore non valido", 'in' => "contiene un valore non valido",
'notIn' => "contiene un valore non valido", 'notIn' => "contiene un valore non valido",
'ip' => "non è un indirizzo IP valido", 'ip' => "non è un indirizzo IP valido",

View File

@ -10,12 +10,9 @@ return array(
'length' => "は%d文字で入力してください", 'length' => "は%d文字で入力してください",
'min' => "には%sより大きな値を入力してください", 'min' => "には%sより大きな値を入力してください",
'max' => "には%sより小さな値を入力してください", 'max' => "には%sより小さな値を入力してください",
'listContains' => "には選択できない値が含まれています",
'in' => "には選択できない値が含まれています", 'in' => "には選択できない値が含まれています",
'notIn' => "には選択できない値が含まれています", 'notIn' => "には選択できない値が含まれています",
'ip' => "はIPアドレスの書式として正しくありません", 'ip' => "はIPアドレスの書式として正しくありません",
'ipv4' => "はIPv4のIPアドレスの書式として正しくありません",
'ipv6' => "はIPv6のIPアドレスの書式として正しくありません",
'email' => "はメールアドレスの書式として正しくありません", 'email' => "はメールアドレスの書式として正しくありません",
'url' => "はURLの書式として正しくありません", 'url' => "はURLの書式として正しくありません",
'urlActive' => "はアクティブなドメインではありません", 'urlActive' => "はアクティブなドメインではありません",
@ -34,9 +31,4 @@ return array(
'lengthMin' => "は%d文字以上入力してください", 'lengthMin' => "は%d文字以上入力してください",
'lengthMax' => "は%d文字以内で入力してください", 'lengthMax' => "は%d文字以内で入力してください",
'instanceOf' => "は「%s」のインスタンスではありません", 'instanceOf' => "は「%s」のインスタンスではありません",
'containsUnique' => "は重複のないように入力してください",
'requiredWith' => "を入力してください",
'requiredWithout' => "を入力してください",
'subset' => "には選択できない値が含まれています",
'arrayHasKeys' => "の必要な項目が選択されていません",
); );

View File

@ -10,7 +10,6 @@ return array(
'length' => "의 길이는 %d 이어야 합니다.", 'length' => "의 길이는 %d 이어야 합니다.",
'min' => "은(는) %s 이상이어야 합니다.", 'min' => "은(는) %s 이상이어야 합니다.",
'max' => "은(는) %s 이하여야 합니다.", 'max' => "은(는) %s 이하여야 합니다.",
'listContains' => "은(는) 올바르지 않은 값을 포함하고 있습니다.",
'in' => "은(는) 올바르지 않은 값을 포함하고 있습니다.", 'in' => "은(는) 올바르지 않은 값을 포함하고 있습니다.",
'notIn' => "은(는) 올바르지 않은 값을 포함하고 있습니다.", 'notIn' => "은(는) 올바르지 않은 값을 포함하고 있습니다.",
'ip' => "은(는) 올바르지 않은 IP입니다.", 'ip' => "은(는) 올바르지 않은 IP입니다.",

View File

@ -9,7 +9,6 @@ return array(
'length' => "turi būti %d ženklų ilgio", 'length' => "turi būti %d ženklų ilgio",
'min' => "turi būti bent %s", 'min' => "turi būti bent %s",
'max' => "turi būti ne daugiau kaip %s", 'max' => "turi būti ne daugiau kaip %s",
'listContains' => "turi neteisingą vertę",
'in' => "turi neteisingą vertę", 'in' => "turi neteisingą vertę",
'notIn' => "turi neteisingą vertę", 'notIn' => "turi neteisingą vertę",
'ip' => "nėra teisingas IP adresas", 'ip' => "nėra teisingas IP adresas",

View File

@ -10,7 +10,6 @@ return array(
'length' => "nedrīkst būt garāks par %d simboliem", 'length' => "nedrīkst būt garāks par %d simboliem",
'min' => "jābūt garākam par %s simboliem", 'min' => "jābūt garākam par %s simboliem",
'max' => "jābūt īsākam par %s simboliem", 'max' => "jābūt īsākam par %s simboliem",
'listContains' => "lauks satur nederīgu vērtību",
'in' => "lauks satur nederīgu vērtību", 'in' => "lauks satur nederīgu vērtību",
'notIn' => "lauks satur nederīgu vērtību", 'notIn' => "lauks satur nederīgu vērtību",
'ip' => " lauks nav derīga IP adrese", 'ip' => " lauks nav derīga IP adrese",

View File

@ -10,7 +10,6 @@ return array(
'length' => "må være %d tegn langt", 'length' => "må være %d tegn langt",
'min' => "må være minst %s", 'min' => "må være minst %s",
'max' => "må ikke være mer enn %s", 'max' => "må ikke være mer enn %s",
'listContains' => "inneholder ugyldig verdi",
'in' => "inneholder ugyldig verdi", 'in' => "inneholder ugyldig verdi",
'notIn' => "inneholder ugyldig verdi", 'notIn' => "inneholder ugyldig verdi",
'ip' => "er ikke en gyldig IP adresse", 'ip' => "er ikke en gyldig IP adresse",

View File

@ -10,7 +10,6 @@ return array(
'length' => "moet minstens %d karakters lang zijn", 'length' => "moet minstens %d karakters lang zijn",
'min' => "moet minstens %s zijn", 'min' => "moet minstens %s zijn",
'max' => "mag niet meer zijn dan %s", 'max' => "mag niet meer zijn dan %s",
'listContains' => "bevat een ongeldige waarde",
'in' => "bevat een ongeldige waarde", 'in' => "bevat een ongeldige waarde",
'notIn' => "bevat een ongeldige waarde", 'notIn' => "bevat een ongeldige waarde",
'ip' => "is geen geldig IP-adres", 'ip' => "is geen geldig IP-adres",

View File

@ -10,7 +10,6 @@ return array(
'length' => "må være %d tegn", 'length' => "må være %d tegn",
'min' => "må være minst %s", 'min' => "må være minst %s",
'max' => "må ikke være mer enn %s", 'max' => "må ikke være mer enn %s",
'listContains' => "inneholder ugyldig verdi",
'in' => "inneholder ugyldig verdi", 'in' => "inneholder ugyldig verdi",
'notIn' => "inneholder ugyldig verdi", 'notIn' => "inneholder ugyldig verdi",
'ip' => "er ikkje ein gyldig IP Adresse", 'ip' => "er ikkje ein gyldig IP Adresse",

View File

@ -10,7 +10,6 @@ return array(
'length' => "musi być dłuższe niż %d", 'length' => "musi być dłuższe niż %d",
'min' => "musi być przynajmniej %s", 'min' => "musi być przynajmniej %s",
'max' => "nie może być większe niż %s", 'max' => "nie może być większe niż %s",
'listContains' => "zawiera nieprawidłową wartość",
'in' => "zawiera nieprawidłową wartość", 'in' => "zawiera nieprawidłową wartość",
'notIn' => "zawiera nieprawidłową wartość", 'notIn' => "zawiera nieprawidłową wartość",
'ip' => "nie jest prawidłowym adresem IP", 'ip' => "nie jest prawidłowym adresem IP",

View File

@ -30,8 +30,5 @@ return array(
'creditCard' => "deve ser um numero de cartão de credito válido", 'creditCard' => "deve ser um numero de cartão de credito válido",
'lengthMin' => "deve ter ao menos %d caracteres", 'lengthMin' => "deve ter ao menos %d caracteres",
'lengthMax' => "não deve exceder %d caracteres", 'lengthMax' => "não deve exceder %d caracteres",
'instanceOf' => "deve ser uma instância de '%s'", 'instanceOf' => "deve ser uma instância de '%s'"
'containsUnique' => "deve conter apenas valores únicos",
'subset' => "contém um item que não está na lista",
'arrayHasKeys' => "não contém todas as chaves requeridas"
); );

View File

@ -10,7 +10,6 @@ return array(
'length' => "trebuie sa fie mai lung decat %d", 'length' => "trebuie sa fie mai lung decat %d",
'min' => "trebuie sa fie cel putin %s", 'min' => "trebuie sa fie cel putin %s",
'max' => "nu trebuie sa fie mai mult de %s", 'max' => "nu trebuie sa fie mai mult de %s",
'listContains' => "contine caractere invalide",
'in' => "contine caractere invalide", 'in' => "contine caractere invalide",
'notIn' => "contine o valoare invalida", 'notIn' => "contine o valoare invalida",
'ip' => "nu este o adresa IP valida", 'ip' => "nu este o adresa IP valida",

View File

@ -10,7 +10,6 @@ return array(
'length' => "должно быть длиннее, чем %d", 'length' => "должно быть длиннее, чем %d",
'min' => "должно быть не менее, чем %s", 'min' => "должно быть не менее, чем %s",
'max' => "должно быть не более, чем %s", 'max' => "должно быть не более, чем %s",
'listContains' => "содержит неверное значение",
'in' => "содержит неверное значение", 'in' => "содержит неверное значение",
'notIn' => "содержит неверное значение", 'notIn' => "содержит неверное значение",
'ip' => "не является валидным IP адресом", 'ip' => "не является валидным IP адресом",

View File

@ -10,7 +10,6 @@ return array(
'length' => "musí byť dlhý aspoň %d", 'length' => "musí byť dlhý aspoň %d",
'min' => "musí byť dlhý minimálne %s", 'min' => "musí byť dlhý minimálne %s",
'max' => "musí byť maximálne %s", 'max' => "musí byť maximálne %s",
'listContains' => "obsahuje nepovolenú hodnotu",
'in' => "obsahuje nepovolenú hodnotu", 'in' => "obsahuje nepovolenú hodnotu",
'notIn' => "obsahuje nepovolenú hodnotu", 'notIn' => "obsahuje nepovolenú hodnotu",
'ip' => "nie je korektná IP adresa", 'ip' => "nie je korektná IP adresa",

View File

@ -1,42 +0,0 @@
<?php
return array(
'required' => "potrebno",
'equals' => "mora biti enak '% s'",
'different' => "mora biti drugačen od '% s'",
'accepted' => "mora biti označeno",
'numeric' => "mora biti številka",
'integer' => "mora biti celo število",
'length' => "ne sme biti daljši od% d",
'min' => "mora biti večji od% s",
'max' => "mora biti manjši od% s",
'listContains' => "vsebuje neveljavno vrednost",
'in' => "vsebuje neveljavno vrednost",
'notIn' => "vsebuje neveljavno vrednost",
'ip' => "ni veljaven naslov IP",
'ipv4' => "ni veljaven naslov IPv4",
'ipv6' => "ni veljaven naslov IPv6",
'email' => "ni veljaven e-poštni naslov",
'url' => "ni veljaven URL",
'urlActive' => "mora biti aktivna domena",
'alpha' => "mora vsebovati samo črke a-z",
'alphaNum' => "mora vsebovati samo črke a-z in / ali številke 0-9",
'slug' => "mora vsebovati samo črke a-z, številke 0-9, črtice in podčrtaje",
'regex' => "vsebuje neveljavne znake",
'date' => "ni veljaven datum",
'dateFormat' => "mora biti datum s formatom '% s'",
'dateBefore' => "mora biti datum pred '% s'",
'dateAfter' => "mora biti datum za '% s'",
'contains' => "mora vsebovati% s",
'boolean' => "mora biti boolean",
'lengthBetween' => "mora biti med% d in% d znaki",
'creditCard' => "mora biti veljavna številka kreditne kartice",
'lengthMin' => "mora biti dolg vsaj% d znakov",
'lengthMax' => "ne sme presegati% d znakov",
'instanceOf' => "mora biti primerek '% s'",
'containsUnique' => "mora vsebovati samo edinstvene elemente",
'requiredWith' => "je potrebno",
'requiredWithout'=> "je potrebno",
'subset' => "vsebuje element, ki ga ni na seznamu",
'arrayHasKeys' => "ne vsebuje vseh potrebnih tipk",
);

View File

@ -10,26 +10,25 @@ return array(
'length' => "måste vara %d tecken långt", 'length' => "måste vara %d tecken långt",
'min' => "måste vara minst %s", 'min' => "måste vara minst %s",
'max' => "får inte vara mer än %s", 'max' => "får inte vara mer än %s",
'listContains' => "innehåller ogiltigt värde",
'in' => "innehåller ogiltigt värde", 'in' => "innehåller ogiltigt värde",
'notIn' => "innehåller ogiltigt värde", 'notIn' => "innehåller ogiltigt värde",
'ip' => "är inte en giltig IP-adress", 'ip' => "är inte en giltlig IP-adress",
'email' => "är inte en giltig e-postadress", 'email' => "är inte en giltlig e-postadress",
'url' => "är inte en giltig URL", 'url' => "är inte en giltlig URL",
'urlActive' => "måste vara ett aktivt domännamn", 'urlActive' => "måste vara ett aktivt domännamn",
'alpha' => "får bara innehålla bokstäver a-z", 'alpha' => "får bara inehålla bokstäver a-z",
'alphaNum' => "får bara innehålla bokstäver a-z och/eller siffror 0-9", 'alphaNum' => "får bara inehålla bokstäver a-z och/eller siffror 0-9",
'slug' => "får bara innehålla bokstäver a-z och/eller siffror 0-9, bindesstreck och understreck", 'slug' => "får bara inehålla bokstäver a-z och/eller siffror 0-9, bindesträck og understräck",
'regex' => "innehåller ogiltiga tecken", 'regex' => "inehåller ogiltliga tecken",
'date' => "är inte ett giltigt datum", 'date' => "är inte ett giltligt datum",
'dateFormat' => "måste vara ett datum med formatet '%s'", 'dateFormat' => "måste vara ett datum med formatet '%s'",
'dateBefore' => "måste vara ett datum före '%s'", 'dateBefore' => "måste vara ett datum före '%s'",
'dateAfter' => "måste vara ett datum efter '%s'", 'dateAfter' => "måste vara ett datum efter '%s'",
'contains' => "måste innehålla %s", 'contains' => "måste innehålla %s",
'boolean' => "måste vara ett booleskt värde", 'boolean' => "måste vara ett booleskt värde",
'lengthBetween' => "måste vara mellan %d och %d tecken långt", 'lengthBetween' => "måste vara mellan %d och %d tecken långt",
'creditCard' => "måste vara ett giltigt kreditkortsnummer", 'creditCard' => "måste vara et gyldig kredittkortnummer",
'lengthMin' => "måste vara minst %d tecken långt", 'lengthMin' => "måste vara minst %d tecken långt",
'lengthMax' => "får inte överstiga %d tecken", 'lengthMax' => "får itne överstiga %d tecken",
'instanceOf' => "måste vara en instans av '%s'" 'instanceOf' => "måste vara en instans av '%s'"
); );

View File

@ -10,7 +10,6 @@ return array(
'length' => "ต้องมีความยาวมากกว่า %d", 'length' => "ต้องมีความยาวมากกว่า %d",
'min' => "ต้องมีอย่างน้อย %s", 'min' => "ต้องมีอย่างน้อย %s",
'max' => "ต้องไม่มากเกิน %s", 'max' => "ต้องไม่มากเกิน %s",
'listContains' => "ประกอบด้วยค่าที่ไม่ถูกต้อง",
'in' => "ประกอบด้วยค่าที่ไม่ถูกต้อง", 'in' => "ประกอบด้วยค่าที่ไม่ถูกต้อง",
'notIn' => "ประกอบด้วยค่าที่ไม่ถูกต้อง", 'notIn' => "ประกอบด้วยค่าที่ไม่ถูกต้อง",
'ip' => "ไม่ใช่ IP ที่ถูกต้อง", 'ip' => "ไม่ใช่ IP ที่ถูกต้อง",

View File

@ -10,7 +10,6 @@ return array(
'length' => "en az %d adet uzunluğunda olmalı", 'length' => "en az %d adet uzunluğunda olmalı",
'min' => "en az böyle olmalı %s", 'min' => "en az böyle olmalı %s",
'max' => "bundan daha fazla olmalı %s", 'max' => "bundan daha fazla olmalı %s",
'listContains' => "geçersiz değer içeriyor",
'in' => "geçersiz değer içeriyor", 'in' => "geçersiz değer içeriyor",
'notIn' => "geçersiz değer içeriyor", 'notIn' => "geçersiz değer içeriyor",
'ip' => "geçerli bir IP adresi değil", 'ip' => "geçerli bir IP adresi değil",
@ -29,7 +28,7 @@ return array(
'boolean' => "boolean olmalı", 'boolean' => "boolean olmalı",
'lengthBetween' => "%d ve %d karakter arasında olmalı", 'lengthBetween' => "%d ve %d karakter arasında olmalı",
'creditCard' => "geçerli bir kredi kartı numarası olmalı", 'creditCard' => "geçerli bir kredi kartı numarası olmalı",
"lengthMin" => "%d karakterden fazla içermeli", "lengthMin" => "%d katakterden fazla içermeli",
"lengthMax" => "%d karakterden az içermeli", "lengthMax" => "%d karakterden az içermeli",
"instanceOf" => "bunun bir örneği olmalı '%s'" "instanceOf" => "bunun bir örneği olmalı '%s'"
); );

View File

@ -10,7 +10,6 @@ return array(
'length' => "має бути довшим, ніж %d", 'length' => "має бути довшим, ніж %d",
'min' => "має бути більше, ніж %s", 'min' => "має бути більше, ніж %s",
'max' => "повинно бути менше, ніж %s", 'max' => "повинно бути менше, ніж %s",
'listContains' => "містить невірне значення",
'in' => "містить невірне значення", 'in' => "містить невірне значення",
'notIn' => "містить невірне значення", 'notIn' => "містить невірне значення",
'ip' => "не є валідною IP адресою", 'ip' => "не є валідною IP адресою",

View File

@ -10,7 +10,6 @@ return array(
'length' => "phải dài hơn %d", 'length' => "phải dài hơn %d",
'min' => "ít nhất %s", 'min' => "ít nhất %s",
'max' => "tối đa %s", 'max' => "tối đa %s",
'listContains' => "chứa giá trị không hợp lệ",
'in' => "chứa giá trị không hợp lệ", 'in' => "chứa giá trị không hợp lệ",
'notIn' => "chứa giá trị không hợp lệ", 'notIn' => "chứa giá trị không hợp lệ",
'ip' => "địa chỉ IP không hợp lệ", 'ip' => "địa chỉ IP không hợp lệ",

View File

@ -7,10 +7,9 @@ return array(
'accepted' => "必须接受", 'accepted' => "必须接受",
'numeric' => "只能是数字", 'numeric' => "只能是数字",
'integer' => "只能是整数", 'integer' => "只能是整数",
'length' => "长度必须于 %d", 'length' => "长度必须于 %d",
'min' => "必须大于 %s", 'min' => "必须大于 %s",
'max' => "必须小于 %s", 'max' => "必须小于 %s",
'listContains' => "无效的值",
'in' => "无效的值", 'in' => "无效的值",
'notIn' => "无效的值", 'notIn' => "无效的值",
'ip' => "无效IP地址", 'ip' => "无效IP地址",
@ -30,11 +29,5 @@ return array(
'lengthBetween' => "长度只能介于 %d 和 %d 之间", 'lengthBetween' => "长度只能介于 %d 和 %d 之间",
'creditCard' => "信用卡号码不正确", 'creditCard' => "信用卡号码不正确",
'lengthMin' => "长度必须大于 %d", 'lengthMin' => "长度必须大于 %d",
'lengthMax' => "长度必须小于 %d", 'lengthMax' => "长度必须小于 %d"
'instanceOf' => "必须是 '%s' 的实例",
'containsUnique' => "必须仅包含唯一的元素",
'requiredWith' => "是必须的",
'requiredWithout' => "是必须的",
'subset' => "包含不在列表中的项目",
'arrayHasKeys' => "不包含所有必需的键",
); );

View File

@ -10,7 +10,6 @@ return array(
'length' => "長度必須大於 %d", 'length' => "長度必須大於 %d",
'min' => "必須大於 %s", 'min' => "必須大於 %s",
'max' => "必須小於 %s", 'max' => "必須小於 %s",
'listContains' => "無效的值",
'in' => "無效的值", 'in' => "無效的值",
'notIn' => "無效的值", 'notIn' => "無效的值",
'ip' => "無效IP地址", 'ip' => "無效IP地址",
@ -25,16 +24,5 @@ return array(
'dateFormat' => "日期的格式應該為 '%s'", 'dateFormat' => "日期的格式應該為 '%s'",
'dateBefore' => "日期必須在 '%s' 之前", 'dateBefore' => "日期必須在 '%s' 之前",
'dateAfter' => "日期必須在 '%s' 之後", 'dateAfter' => "日期必須在 '%s' 之後",
'contains' => "必須包含 %s", 'contains' => "必須包含 %s"
'boolean' => "必須是真或假",
'lengthBetween' => "長度只能介於 %d 和 %d 之間",
'creditCard' => "信用卡號碼不正確",
'lengthMin' => "長度必須大於 %d",
'lengthMax' => "長度必須小於 %d",
'instanceOf' => "必須是 '%s' 的實例",
'containsUnique' => "必須僅包含唯一的元素",
'requiredWith' => "是必須的",
'requiredWithout' => "是必須的",
'subset' => "包含不在列表中的項目",
'arrayHasKeys' => "不包含所有必需的鍵",
); );

View File

@ -7,6 +7,7 @@
convertWarningsToExceptions="true" convertWarningsToExceptions="true"
processIsolation="false" processIsolation="false"
stopOnFailure="false" stopOnFailure="false"
syntaxCheck="false"
bootstrap="tests/bootstrap.php" bootstrap="tests/bootstrap.php"
> >
<testsuites> <testsuites>
@ -14,4 +15,12 @@
<directory suffix="Test.php">tests/Valitron</directory> <directory suffix="Test.php">tests/Valitron</directory>
</testsuite> </testsuite>
</testsuites> </testsuites>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
<blacklist>
<directory suffix=".php">vendor/</directory>
</blacklist>
</filter>
</phpunit> </phpunit>

View File

@ -83,11 +83,6 @@ class Validator
*/ */
protected $stop_on_first_fail = false; protected $stop_on_first_fail = false;
/**
* @var bool
*/
protected $prepend_labels = true;
/** /**
* Setup validation * Setup validation
* *
@ -149,14 +144,6 @@ class Validator
return static::$_langDir ?: dirname(dirname(__DIR__)) . '/lang'; return static::$_langDir ?: dirname(dirname(__DIR__)) . '/lang';
} }
/**
* @param bool $prepend_labels
*/
public function setPrependLabels($prepend_labels = true)
{
$this->prepend_labels = $prepend_labels;
}
/** /**
* Required field validator * Required field validator
* *
@ -172,7 +159,9 @@ class Validator
return $find[1]; return $find[1];
} }
if (is_null($value) || (is_string($value) && trim($value) === '')) { if (is_null($value)) {
return false;
} elseif (is_string($value) && trim($value) === '') {
return false; return false;
} }
@ -420,12 +409,8 @@ class Validator
*/ */
protected function validateIn($field, $value, $params) protected function validateIn($field, $value, $params)
{ {
$forceAsAssociative = false; $isAssoc = array_values($params[0]) !== $params[0];
if (isset($params[2])) { if ($isAssoc) {
$forceAsAssociative = (bool) $params[2];
}
if ($forceAsAssociative || $this->isAssociativeArray($params[0])) {
$params[0] = array_keys($params[0]); $params[0] = array_keys($params[0]);
} }
@ -437,33 +422,6 @@ class Validator
return in_array($value, $params[0], $strict); return in_array($value, $params[0], $strict);
} }
/**
* Validate a field is contained within a list of values
*
* @param string $field
* @param mixed $value
* @param array $params
* @return bool
*/
protected function validateListContains($field, $value, $params)
{
$forceAsAssociative = false;
if (isset($params[2])) {
$forceAsAssociative = (bool) $params[2];
}
if ($forceAsAssociative || $this->isAssociativeArray($value)) {
$value = array_keys($value);
}
$strict = false;
if (isset($params[1])) {
$strict = $params[1];
}
return in_array($params[0], $value, $strict);
}
/** /**
* Validate a field is not contained within a list of values * Validate a field is not contained within a list of values
* *
@ -531,7 +489,7 @@ class Validator
if (!is_array($params[0])) { if (!is_array($params[0])) {
$params[0] = array($params[0]); $params[0] = array($params[0]);
} }
if (is_scalar($value) || is_null($value)) { if (is_scalar($value)) {
return $this->validateIn($field, $value, $params); return $this->validateIn($field, $value, $params);
} }
@ -630,17 +588,12 @@ class Validator
*/ */
protected function validateEmailDNS($field, $value) protected function validateEmailDNS($field, $value)
{ {
if (!is_string($value)) {
return false;
}
if ($this->validateEmail($field, $value)) { if ($this->validateEmail($field, $value)) {
$domain = ltrim(stristr($value, '@'), '@') . '.'; $domain = ltrim(stristr($value, '@'), '@') . '.';
if (function_exists('idn_to_ascii') && defined('INTL_IDNA_VARIANT_UTS46')) { if (function_exists('idn_to_ascii') && defined('INTL_IDNA_VARIANT_UTS46')) {
$domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46); $domain = idn_to_ascii($domain, 0, INTL_IDNA_VARIANT_UTS46);
} }
return checkdnsrr($domain, 'ANY');
return checkdnsrr($domain, 'MX');
} }
return false; return false;
@ -655,10 +608,6 @@ class Validator
*/ */
protected function validateUrl($field, $value) protected function validateUrl($field, $value)
{ {
if (!is_string($value)) {
return false;
}
foreach ($this->validUrlPrefixes as $prefix) { foreach ($this->validUrlPrefixes as $prefix) {
if (strpos($value, $prefix) !== false) { if (strpos($value, $prefix) !== false) {
return filter_var($value, \FILTER_VALIDATE_URL) !== false; return filter_var($value, \FILTER_VALIDATE_URL) !== false;
@ -677,10 +626,6 @@ class Validator
*/ */
protected function validateUrlActive($field, $value) protected function validateUrlActive($field, $value)
{ {
if (!is_string($value)) {
return false;
}
foreach ($this->validUrlPrefixes as $prefix) { foreach ($this->validUrlPrefixes as $prefix) {
if (strpos($value, $prefix) !== false) { if (strpos($value, $prefix) !== false) {
$host = parse_url(strtolower($value), PHP_URL_HOST); $host = parse_url(strtolower($value), PHP_URL_HOST);
@ -909,11 +854,13 @@ class Validator
} elseif (isset($cards)) { } elseif (isset($cards)) {
// if we have cards, check our users card against only the ones we have // if we have cards, check our users card against only the ones we have
foreach ($cards as $card) { foreach ($cards as $card) {
if (in_array($card, array_keys($cardRegex)) && preg_match($cardRegex[$card], $value) === 1) { if (in_array($card, array_keys($cardRegex))) {
// if the card is valid, we want to stop looping // if the card is valid, we want to stop looping
if (preg_match($cardRegex[$card], $value) === 1) {
return true; return true;
} }
} }
}
} else { } else {
// loop through every card // loop through every card
foreach ($cardRegex as $regex) { foreach ($cardRegex as $regex) {
@ -950,94 +897,6 @@ class Validator
return $isInstanceOf; return $isInstanceOf;
} }
/**
* Validates whether or not a field is required based on whether or not other fields are present.
*
* @param string $field name of the field in the data array
* @param mixed $value value of this field
* @param array $params parameters for this rule
* @param array $fields full list of data to be validated
* @return bool
*/
protected function validateRequiredWith($field, $value, $params, $fields)
{
$conditionallyReq = false;
// if we actually have conditionally required with fields to check against
if (isset($params[0])) {
// convert single value to array if it isn't already
$reqParams = is_array($params[0]) ? $params[0] : array($params[0]);
// check for the flag indicating if all fields are required
$allRequired = isset($params[1]) && (bool)$params[1];
$emptyFields = 0;
foreach ($reqParams as $requiredField) {
// check the field is set, not null, and not the empty string
list($requiredFieldValue, $multiple) = $this->getPart($fields, explode('.', $requiredField));
if (isset($requiredFieldValue) && (!is_string($requiredFieldValue) || trim($requiredFieldValue) !== '')) {
if (!$allRequired) {
$conditionallyReq = true;
break;
} else {
$emptyFields++;
}
}
}
// if all required fields are present in strict mode, we're requiring it
if ($allRequired && $emptyFields === count($reqParams)) {
$conditionallyReq = true;
}
}
// if we have conditionally required fields
if ($conditionallyReq && (is_null($value) ||
is_string($value) && trim($value) === '')) {
return false;
}
return true;
}
/**
* Validates whether or not a field is required based on whether or not other fields are present.
*
* @param string $field name of the field in the data array
* @param mixed $value value of this field
* @param array $params parameters for this rule
* @param array $fields full list of data to be validated
* @return bool
*/
protected function validateRequiredWithout($field, $value, $params, $fields)
{
$conditionallyReq = false;
// if we actually have conditionally required with fields to check against
if (isset($params[0])) {
// convert single value to array if it isn't already
$reqParams = is_array($params[0]) ? $params[0] : array($params[0]);
// check for the flag indicating if all fields are required
$allEmpty = isset($params[1]) && (bool)$params[1];
$filledFields = 0;
foreach ($reqParams as $requiredField) {
// check the field is NOT set, null, or the empty string, in which case we are requiring this value be present
list($requiredFieldValue, $multiple) = $this->getPart($fields, explode('.', $requiredField));
if (!isset($requiredFieldValue) || (is_string($requiredFieldValue) && trim($requiredFieldValue) === '')) {
if (!$allEmpty) {
$conditionallyReq = true;
break;
} else {
$filledFields++;
}
}
}
// if all fields were empty, then we're requiring this in strict mode
if ($allEmpty && $filledFields === count($reqParams)) {
$conditionallyReq = true;
}
}
// if we have conditionally required fields
if ($conditionallyReq && (is_null($value) ||
is_string($value) && trim($value) === '')) {
return false;
}
return true;
}
/** /**
* Validate optional field * Validate optional field
* *
@ -1052,23 +911,6 @@ class Validator
return true; return true;
} }
protected function validateArrayHasKeys($field, $value, $params)
{
if (!is_array($value) || !isset($params[0])) {
return false;
}
$requiredFields = $params[0];
if (count($requiredFields) === 0) {
return false;
}
foreach ($requiredFields as $fieldName) {
if (!array_key_exists($fieldName, $value)) {
return false;
}
}
return true;
}
/** /**
* Get array of fields and data * Get array of fields and data
* *
@ -1119,9 +961,11 @@ class Validator
} }
} }
// Use custom label instead of field name if set // Use custom label instead of field name if set
if (is_string($params[0]) && isset($this->_labels[$param])) { if (is_string($params[0])) {
if (isset($this->_labels[$param])) {
$param = $this->_labels[$param]; $param = $this->_labels[$param];
} }
}
$values[] = $param; $values[] = $param;
} }
@ -1195,27 +1039,6 @@ class Validator
} }
} }
private function validationMustBeExcecuted($validation, $field, $values, $multiple){
//always excecute requiredWith(out) rules
if (in_array($validation['rule'], array('requiredWith', 'requiredWithout'))){
return true;
}
//do not execute if the field is optional and not set
if($this->hasRule('optional', $field) && ! isset($values)){
return false;
}
//ignore empty input, except for required and accepted rule
if (! $this->hasRule('required', $field) && ! in_array($validation['rule'], array('required', 'accepted'))){
if($multiple){
return count($values) != 0;
}
return (isset($values) && $values !== '');
}
return true;
}
/** /**
* Run validations and return boolean result * Run validations and return boolean result
* *
@ -1228,7 +1051,14 @@ class Validator
foreach ($v['fields'] as $field) { foreach ($v['fields'] as $field) {
list($values, $multiple) = $this->getPart($this->_fields, explode('.', $field), false); list($values, $multiple) = $this->getPart($this->_fields, explode('.', $field), false);
if (! $this->validationMustBeExcecuted($v, $field, $values, $multiple)){ // Don't validate if the field is not required and the value is empty
if ($this->hasRule('optional', $field) && isset($values)) {
//Continue with execution below if statement
} elseif (
$v['rule'] !== 'required' && !$this->hasRule('required', $field) &&
$v['rule'] !== 'accepted' &&
(!isset($values) || $values === '' || ($multiple && count($values) == 0))
) {
continue; continue;
} }
@ -1306,10 +1136,12 @@ class Validator
protected function hasRule($name, $field) protected function hasRule($name, $field)
{ {
foreach ($this->_validations as $validation) { foreach ($this->_validations as $validation) {
if ($validation['rule'] == $name && in_array($field, $validation['fields'])) { if ($validation['rule'] == $name) {
if (in_array($field, $validation['fields'])) {
return true; return true;
} }
} }
}
return false; return false;
} }
@ -1397,7 +1229,7 @@ class Validator
/** /**
* Convenience method to add a single validation rule * Convenience method to add a single validation rule
* *
* @param string|callable $rule * @param string|callback $rule
* @param array|string $fields * @param array|string $fields
* @return Validator * @return Validator
* @throws \InvalidArgumentException * @throws \InvalidArgumentException
@ -1497,9 +1329,7 @@ class Validator
} }
} }
} else { } else {
$message = $this->prepend_labels $message = str_replace('{field}', ucwords(str_replace('_', ' ', $field)), $message);
? str_replace('{field}', ucwords(str_replace('_', ' ', $field)), $message)
: str_replace('{field} ', '', $message);
} }
return $message; return $message;
@ -1586,9 +1416,4 @@ class Validator
$me->mapFieldRules($field, $rules[$field]); $me->mapFieldRules($field, $rules[$field]);
}, array_keys($rules)); }, array_keys($rules));
} }
private function isAssociativeArray($input){
//array contains at least one key that's not an can not be cast to an integer
return count(array_filter(array_keys($input), 'is_string')) > 0;
}
} }

View File

@ -4,8 +4,10 @@ use PHPUnit\Framework\TestCase;
class BaseTestCase extends TestCase class BaseTestCase extends TestCase
{ {
public function setUp()
{
}
/*
public function tearDown() public function tearDown()
{ {
$this->resetProperty('_lang'); $this->resetProperty('_lang');
@ -21,5 +23,4 @@ class BaseTestCase extends TestCase
$prop->setValue($value); $prop->setValue($value);
$prop->setAccessible(false); $prop->setAccessible(false);
} }
*/
} }

View File

@ -12,19 +12,6 @@ class ErrorMessagesTest extends BaseTestCase
$this->assertSame(array("Name is required"), $v->errors('name')); $this->assertSame(array("Name is required"), $v->errors('name'));
} }
/**
* Test the disabling of prepending the field labels
* to error messages.
*/
public function testErrorMessageExcludeFieldName()
{
$v = new Validator(array());
$v->setPrependLabels(false);
$v->rule('required', 'name');
$v->validate();
$this->assertSame(array("is required"), $v->errors('name'));
}
public function testAccurateErrorMessageParams() public function testAccurateErrorMessageParams()
{ {
$v = new Validator(array('num' => 5)); $v = new Validator(array('num' => 5));

View File

@ -15,8 +15,8 @@ class LangTest extends BaseTestCase
{ {
$lang = 'ar'; $lang = 'ar';
Validator::lang($lang); Validator::lang($lang);
$validator = new Validator(array());
$this->assertEquals($lang, Validator::lang()); $this->assertEquals($lang, Validator::lang());
Validator::lang('en');
} }
/** /**
@ -42,15 +42,13 @@ class LangTest extends BaseTestCase
$this->assertEquals(realpath($this->getLangDir()), realpath(Validator::langDir())); $this->assertEquals(realpath($this->getLangDir()), realpath(Validator::langDir()));
} }
/**
* @expectedException InvalidArgumentException
* @expectedExceptionMessage Fail to load language file '/this/dir/does/not/exists/en.php'
*/
public function testLangException() public function testLangException()
{ {
try{
new Validator(array(), array(), 'en', '/this/dir/does/not/exists'); new Validator(array(), array(), 'en', '/this/dir/does/not/exists');
} catch (Exception $exception){
$this->assertInstanceOf("InvalidArgumentException", $exception);
$this->assertEquals("Fail to load language file '/this/dir/does/not/exists/en.php'", $exception->getMessage());
}
} }

View File

@ -10,7 +10,6 @@ class StaticVsInstanceTest extends BaseTestCase
$this->assertEquals( $this->assertEquals(
'ar', Validator::lang(), 'instance defined lang should not replace static global lang' 'ar', Validator::lang(), 'instance defined lang should not replace static global lang'
); );
Validator::lang('en');
} }
/** /**

View File

@ -726,35 +726,6 @@ class ValidateTest extends BaseTestCase
$this->assertFalse($v->validate()); $this->assertFalse($v->validate());
} }
public function testListContainsValid()
{
$v = new Validator(array('color' => array('blue', 'green', 'red', 'yellow')));
$v->rule('listContains', 'color', 'red');
$this->assertTrue($v->validate());
}
public function testListContainsValidAltSyntax()
{
$v = new Validator(array('color' => array('blue', 'green', 'red')));
$v->rules(array(
'listContains' => array(
array('color', 'red')
)
));
$this->assertTrue($v->validate());
}
public function testListContainsInvalidAltSyntax()
{
$v = new Validator(array('color' => array('blue', 'green', 'red')));
$v->rules(array(
'listContains' => array(
array('color', 'yellow')
)
));
$this->assertFalse($v->validate());
}
public function testInValid() public function testInValid()
{ {
$v = new Validator(array('color' => 'green')); $v = new Validator(array('color' => 'green'));
@ -980,7 +951,6 @@ class ValidateTest extends BaseTestCase
array('color', array('blue', 'green', 'red', 'yellow')) array('color', array('blue', 'green', 'red', 'yellow'))
) )
)); ));
$this->assertFalse($v->validate());
} }
public function testAsciiValid() public function testAsciiValid()
@ -1750,15 +1720,6 @@ class ValidateTest extends BaseTestCase
$this->assertFalse($v->validate()); $this->assertFalse($v->validate());
} }
public function testSubsetAcceptNullValue()
{
// rule value equals null
$v = new Validator(array('test_field' => null));
$v->rule('required', 'test_field');
$v->rule('subset', 'test_field', array('black', 45));
$this->assertFalse($v->validate());
}
public function testContainsUniqueValid() public function testContainsUniqueValid()
{ {
// numeric values // numeric values
@ -2259,338 +2220,6 @@ class ValidateTest extends BaseTestCase
$this->assertFalse($v->validate()); $this->assertFalse($v->validate());
} }
public function testRequiredWithValid()
{
$v = new Validator(array('username' => 'tester', 'password' => 'mypassword'));
$v->rule('requiredWith', 'password', 'username');
$this->assertTrue($v->validate());
}
public function testRequiredWithValidNoParams()
{
$v = new Validator(array());
$v->rule('requiredWith', 'password', 'username');
$this->assertTrue($v->validate());
}
public function testRequiredWithValidEmptyString()
{
$v = new Validator(array('username' => ''));
$v->rule('requiredWith', 'password', 'username');
$this->assertTrue($v->validate());
}
public function testRequiredWithValidNullValue()
{
$v = new Validator(array('username' => null));
$v->rule('requiredWith', 'password', 'username');
$this->assertTrue($v->validate());
}
public function testRequiredWithValidAltSyntax()
{
$v = new Validator(array('username' => 'tester', 'password' => 'mypassword'));
$v->rules(array(
'requiredWith' => array(
array('password', 'username')
)
));
$this->assertTrue($v->validate());
}
public function testRequiredWithValidArray()
{
$v = new Validator(array('username' => 'tester', 'email' => 'test@test.com', 'password' => 'mypassword'));
$v->rule('requiredWith', 'password', array('username', 'email'));
$this->assertTrue($v->validate());
}
public function testRequiredWithStrictValidArray()
{
$v = new Validator(array('username' => 'tester', 'email' => 'test@test.com', 'password' => 'mypassword'));
$v->rule('requiredWith', 'password', array('username', 'email'), true);
$this->assertTrue($v->validate());
}
public function testRequiredWithStrictInvalidArray()
{
$v = new Validator(array('email' => 'test@test.com', 'username' => 'batman'));
$v->rule('requiredWith', 'password', array('username', 'email'), true);
$this->assertFalse($v->validate());
}
public function testRequiredWithStrictValidArrayNotRequired()
{
$v = new Validator(array('username' => 'tester', 'email' => 'test@test.com'));
$v->rule('requiredWith', 'password', array('username', 'email', 'nickname'), true);
$this->assertTrue($v->validate());
}
public function testRequiredWithStrictValidArrayEmptyValues()
{
$v = new Validator(array('email' => '', 'username' => null));
$v->rule('requiredWith', 'password', array('username', 'email'), true);
$this->assertTrue($v->validate());
}
public function testRequiredWithStrictInvalidArraySingleValue()
{
$v = new Validator(array('email' => 'tester', 'username' => null));
$v->rule('requiredWith', 'password', array('username', 'email'), true);
$this->assertTrue($v->validate());
}
public function testRequiredWithValidArrayAltSyntax()
{
$v = new Validator(array('password' => 'mypassword'));
$v->rules(array(
'requiredWith' => array(
array('password', array('username', 'email'))
)
));
$this->assertTrue($v->validate());
}
public function testRequiredWithInvalid()
{
$v = new Validator(array('username' => 'tester'));
$v->rule('requiredWith', 'password', 'username');
$this->assertFalse($v->validate());
}
public function testRequiredWithInvalidAltSyntax()
{
$v = new Validator(array('username' => 'tester'));
$v->rules(array(
'requiredWith' => array(
array('password', 'username')
)
));
$this->assertFalse($v->validate());
}
public function testRequiredWithInvalidArray()
{
$v = new Validator(array('email' => 'test@test.com', 'nickname' => 'kevin'));
$v->rule('requiredWith', 'password', array('username', 'email', 'nickname'));
$this->assertFalse($v->validate());
}
public function testRequiredWithInvalidStrictArray()
{
$v = new Validator(array('email' => 'test@test.com', 'username' => 'batman', 'nickname' => 'james'));
$v->rule('requiredWith', 'password', array('username', 'email', 'nickname'), true);
$this->assertFalse($v->validate());
}
public function testRequiredWithInvalidArrayAltSyntax()
{
$v = new Validator(array('username' => 'tester', 'email' => 'test@test.com'));
$v->rules(array(
'requiredWith' => array(
array('password', array('username', 'email', 'nickname'))
)
));
$this->assertFalse($v->validate());
}
public function testRequiredWithStrictInvalidArrayAltSyntax()
{
$v = new Validator(array('username' => 'tester', 'email' => 'test@test.com', 'nickname' => 'joseph'));
$v->rules(array(
'requiredWith' => array(
array('password', array('username', 'email', 'nickname'), true)
)
));
$this->assertFalse($v->validate());
}
// required without tests
public function testRequiredWithoutValid()
{
$v = new Validator(array('password' => 'mypassword'));
$v->rule('requiredWithout', 'password', 'username');
$this->assertTrue($v->validate());
}
public function testRequiredWithoutInvalidNotPresent()
{
$v = new Validator(array());
$v->rule('requiredWithout', 'password', 'username');
$this->assertFalse($v->validate());
}
public function testRequiredWithoutValidEmptyString()
{
$v = new Validator(array('username' => '', 'password' => 'mypassword'));
$v->rule('requiredWithout', 'password', 'username');
$this->assertTrue($v->validate());
}
public function testRequiredWithoutInvalidEmptyStringNotPresent()
{
$v = new Validator(array('username' => ''));
$v->rule('requiredWithout', 'password', 'username');
$this->assertFalse($v->validate());
}
public function testRequiredWithoutValidNullValue()
{
$v = new Validator(array('username' => null, 'password' => 'mypassword'));
$v->rule('requiredWithout', 'password', 'username');
$this->assertTrue($v->validate());
}
public function testRequiredWithoutInvlidNullValueNotPresent()
{
$v = new Validator(array('username' => null));
$v->rule('requiredWithout', 'password', 'username');
$this->assertFalse($v->validate());
}
public function testRequiredWithoutValidAltSyntax()
{
$v = new Validator(array('password' => 'mypassword'));
$v->rules(array(
'requiredWithout' => array(
array('password', 'username')
)
));
$this->assertTrue($v->validate());
}
public function testRequiredWithoutInvalidAltSyntaxNotPresent()
{
$v = new Validator(array());
$v->rules(array(
'requiredWithout' => array(
array('password', 'username')
)
));
$this->assertFalse($v->validate());
}
public function testRequiredWithoutValidArray()
{
$v = new Validator(array('password' => 'mypassword'));
$v->rule('requiredWithout', 'password', array('username', 'email'));
$this->assertTrue($v->validate());
}
public function testRequiredWithoutInvalidArrayNotPresent()
{
$v = new Validator(array());
$v->rule('requiredWithout', 'password', array('username', 'email'));
$this->assertFalse($v->validate());
}
public function testRequiredWithoutValidArrayPartial()
{
$v = new Validator(array('password' => 'mypassword', 'email' => 'test@test.com'));
$v->rule('requiredWithout', 'password', array('username', 'email'));
$this->assertTrue($v->validate());
}
public function testRequiredWithoutInvalidArrayPartial()
{
$v = new Validator(array('email' => 'test@test.com'));
$v->rule('requiredWithout', 'password', array('username', 'email'));
$this->assertFalse($v->validate());
}
public function testRequiredWithoutValidArrayStrict()
{
$v = new Validator(array('email' => 'test@test.com'));
$v->rule('requiredWithout', 'password', array('username', 'email'), true);
$this->assertTrue($v->validate());
}
public function testRequiredWithoutInvalidArrayStrict()
{
$v = new Validator(array());
$v->rule('requiredWithout', 'password', array('username', 'email'), true);
$this->assertFalse($v->validate());
}
public function testRequiredWithoutInvalidArrayNotProvided()
{
$v = new Validator(array('email' => 'test@test.com'));
$v->rule('requiredWithout', 'password', array('username', 'email'));
$this->assertFalse($v->validate());
}
public function testRequiredWithoutValidArrayAltSyntax()
{
$v = new Validator(array('password' => 'mypassword'));
$v->rules(array(
'requiredWithout' => array(
array('password', array('username', 'email'))
)
));
$this->assertTrue($v->validate());
}
public function testConditionallyRequiredAuthSampleToken()
{
$v = new Validator(array('token' => 'ajkdhieyf2834fsuhf8934y89'));
$v->rule('requiredWithout', 'token', array('email', 'password'));
$v->rule('requiredWith', 'password', 'email');
$v->rule('email', 'email');
$v->rule('optional', 'email');
$this->assertTrue($v->validate());
}
public function testConditionallyRequiredAuthSampleMissingPassword()
{
$v = new Validator(array('email' => 'test@test.com'));
$v->rule('requiredWithout', 'token', array('email', 'password'));
$v->rule('requiredWith', 'password', 'email');
$v->rule('email', 'email');
$v->rule('optional', 'email');
$this->assertFalse($v->validate());
}
public function testConditionallyRequiredAuthSampleTokenAltSyntax()
{
$v = new Validator(array('token' => 'ajkdhieyf2834fsuhf8934y89'));
$v->rules(array(
'requiredWithout' => array(
array('token', array('email', 'password'))
),
'requiredWith' => array(
array('password', array('email'))
),
'email' => array(
array('email')
),
'optional' => array(
array('email')
)
));
$this->assertTrue($v->validate());
}
public function testConditionallyRequiredAuthSampleEmailPasswordAltSyntax()
{
$v = new Validator(array('email' => 'test@test.com', 'password' => 'mypassword'));
$v->rules(array(
'requiredWithout' => array(
array('token', array('email', 'password'))
),
'requiredWith' => array(
array('password', array('email'))
),
'email' => array(
array('email')
),
'optional' => array(
array('email')
)
));
$this->assertTrue($v->validate());
}
/** /**
* @dataProvider dataProviderFor_testError * @dataProvider dataProviderFor_testError
*/ */
@ -2854,112 +2483,6 @@ class ValidateTest extends BaseTestCase
$v->rule('date', 'data.*.foo'); $v->rule('date', 'data.*.foo');
$this->assertFalse($v->validate()); $this->assertFalse($v->validate());
} }
public function testArrayHasKeysTrueIfAllFieldsExist()
{
$v = new Validator(array(
'address' => array(
'name' => 'Jane Doe',
'street' => 'Doe Square',
'city' => 'Doe D.C.'
)
));
$v->rule('arrayHasKeys', 'address', array('name', 'street', 'city'));
$this->assertTrue($v->validate());
}
public function testArrayHasKeysFalseOnMissingField()
{
$v = new Validator(array(
'address' => array(
'name' => 'Jane Doe',
'street' => 'Doe Square'
)
));
$v->rule('arrayHasKeys', 'address', array('name', 'street', 'city'));
$this->assertFalse($v->validate());
}
public function testArrayHasKeysFalseOnNonArray()
{
$v = new Validator(array(
'address' => 'Jane Doe, Doe Square'
));
$v->rule('arrayHasKeys', 'address', array('name', 'street', 'city'));
$this->assertFalse($v->validate());
}
public function testArrayHasKeysFalseOnEmptyRequiredFields()
{
$v = new Validator(array(
'address' => array(
'lat' => 77.547,
'lon' => 16.337
)
));
$v->rule('arrayHasKeys', 'address', array());
$this->assertFalse($v->validate());
}
public function testArrayHasKeysFalseOnUnspecifiedRequiredFields()
{
$v = new Validator(array(
'address' => array(
'lat' => 77.547,
'lon' => 16.337
)
));
$v->rule('arrayHasKeys', 'address');
$this->assertFalse($v->validate());
}
public function testArrayHasKeysTrueIfMissingAndOptional()
{
$v = new Validator(array());
$v->rule('arrayHasKeys', 'address', array('name', 'street', 'city'));
$v->rule('optional', 'address');
$this->assertTrue($v->validate());
}
/**
*
* @see https://github.com/vlucas/valitron/issues/332
*/
public function testInRuleSearchesValuesForNumericArray(){
$v = new Valitron\Validator(array('color' => 'purple'));
$v->rules(array(
'in' => array(
array('color', array(3=>'green', 2=>'purple'))
)
));
$this->assertTrue($v->validate());
}
public function testInRuleSearchesKeysForAssociativeArray(){
$v = new Valitron\Validator(array('color' => 'c-2'));
$v->rules(array(
'in' => array(
array('color', array('c-3'=>'green', 'c-2'=>'purple'))
)
));
$this->assertTrue($v->validate());
}
public function testInRuleSearchesKeysWhenForcedTo(){
$v = new Valitron\Validator(array('color' => 2));
$v->rules(array(
'in' => array(
array('color', array('3'=>'green', '2'=>'purple'), null, true)
)
));
$this->assertTrue($v->validate());
}
} }
function sampleFunctionCallback($field, $value, array $params) function sampleFunctionCallback($field, $value, array $params)