dev와 composer 버전 일치

This commit is contained in:
2020-03-22 23:22:50 +09:00
parent 869ad39ddc
commit bdcc79ce34
421 changed files with 14006 additions and 16258 deletions
+1
View File
@@ -0,0 +1 @@
tidelift: "packagist/vlucas/valitron"
+940 -8
View File
@@ -99,6 +99,19 @@ if($v->validate()) {
}
```
You can also access nested values using dot notation:
```php
$v = new Valitron\Validator(array('user' => array('first_name' => 'Steve', 'last_name' => 'Smith', 'username' => 'Batman123')));
$v->rule('alpha', 'user.first_name')->rule('alpha', 'user.last_name')->rule('alphaNum', 'user.username');
if($v->validate()) {
echo "Yay! We're all good!";
} else {
// Errors
print_r($v->errors());
}
```
Setting language and language dir globally:
```php
@@ -112,11 +125,36 @@ V::lang('ar');
```
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
* `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)
* `different` - Field must be different than another field
* `accepted` - Checkbox or Radio must be accepted (yes, on, 1, true)
@@ -130,15 +168,19 @@ V::lang('ar');
* `lengthMax` - String must be less than given length
* `min` - Minimum
* `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
* `notIn` - Negation of `in` rule (not in array of values)
* `ip` - Valid IP address
* `ipv4` - Valid IP v4 address
* `ipv6` - Valid IP v6 address
* `email` - Valid email address
* `emailDNS` - Valid email address with active DNS record
* `url` - Valid URL
* `urlActive` - Valid URL with active DNS record
* `alpha` - Alphabetic characters only
* `alphaNum` - Alphabetic and numeric characters only
* `ascii` - ASCII characters only
* `slug` - URL slug characters (a-z, 0-9, -, \_)
* `regex` - Field matches given regex pattern
* `date` - Field is a valid date
@@ -146,9 +188,12 @@ V::lang('ar');
* `dateBefore` - Field is a valid date and is before the given date
* `dateAfter` - Field is a valid date and is after the given date
* `contains` - Field is a string and contains the given string
* `subset` - Field is an array or a scalar and all elements are contained in the given array
* `containsUnique` - Field is an array and contains unique values
* `creditCard` - Field is a valid credit card number
* `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.
* `arrayHasKeys` - Field is an array and contains all specified keys.
**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)
@@ -156,7 +201,7 @@ extension for greater accuracy and reliability. The extension is not required
for Valitron to work, but Valitron will use it if available, and it is highly
recommended.
## Required fields
## required fields usage
the `required` rule checks if a field exists in the data array, and is not null or an empty string.
```php
$v->rule('required', 'field_name');
@@ -166,6 +211,807 @@ Using an extra parameter, you can make this rule more flexible, and only check i
```php
$v->rule('required', 'field_name', true);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'spiderman', 'password' => 'Gr33nG0Blin', 'required_but_null' => null]);
$v->rules([
'required' => [
['username'],
['password'],
['required_but_null', true] // boolean flag allows empty value so long as the field name is set on the data array
]
]);
$v->validate();
```
## requiredWith fields usage
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
The `equals` rule checks if two fields are equals in the data array, and that the second field is not null.
```php
$v->rule('equals', 'password', 'confirmPassword');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['password' => 'youshouldnotseethis', 'confirmPassword' => 'youshouldnotseethis']);
$v->rules([
'equals' => [
['password', 'confirmPassword']
]
]);
$v->validate();
```
## different fields usage
The `different` rule checks if two fields are not the same, or different, in the data array and that the second field is not null.
```php
$v->rule('different', 'username', 'password');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'spiderman', 'password' => 'Gr33nG0Blin']);
$v->rules([
'different' => [
['username', 'password']
]
]);
$v->validate();
```
## accepted fields usage
The `accepted` rule checks if the field is either 'yes', 'on', 1, or true.
```php
$v->rule('accepted', 'remember_me');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['remember_me' => true]);
$v->rules([
'accepted' => [
['remember_me']
]
]);
$v->validate();
```
## numeric fields usage
The `numeric` rule checks if the field is number. This is analogous to php's is_numeric() function.
```php
$v->rule('numeric', 'amount');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['amount' => 3.14]);
$v->rules([
'numeric' => [
['amount']
]
]);
$v->validate();
```
## integer fields usage
The `integer` rule checks if the field is an integer number.
```php
$v->rule('integer', 'age');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['age' => '27']);
$v->rules([
'integer' => [
['age']
]
]);
$v->validate();
```
*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
$v = new Valitron\Validator(['age' => '-27']);
$v->rules([
'integer' => [
['age', true]
]
]);
$v->validate();
```
Whereas the same for a positive (+) value would evaluate to false, as the + in this case is redundant:
```php
$v = new Valitron\Validator(['age' => '+27']);
$v->rules([
'integer' => [
['age', true]
]
]);
$v->validate();
```
## boolean fields usage
The `boolean` rule checks if the field is a boolean. This is analogous to php's is_bool() function.
```php
$v->rule('boolean', 'remember_me');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['remember_me' => true]);
$v->rules([
'boolean' => [
['remember_me']
]
]);
$v->validate();
```
## array fields usage
The `array` rule checks if the field is an array. This is analogous to php's is_array() function.
```php
$v->rule('array', 'user_notifications');
```
Alternate Syntax.
```php
$v = new Valitron\Validator(['user_notifications' => ['bulletin_notifications' => true, 'marketing_notifications' => false, 'message_notification' => true]]);
$v->rules([
'array' => [
['user_notifications']
]
]);
$v->validate();
```
## length fields usage
The `length` rule checks if the field is exactly a given length and that the field is a valid string.
```php
$v->rule('length', 'username', 10);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'bobburgers']);
$v->rules([
'length' => [
['username', 10]
]
]);
$v->validate();
```
## lengthBetween fields usage
The `lengthBetween` rule checks if the field is between a given length tange and that the field is a valid string.
```php
$v->rule('lengthBetween', 'username', 1, 10);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'bobburgers']);
$v->rules([
'lengthBetween' => [
['username', 1, 10]
]
]);
$v->validate();
```
## lengthMin fields usage
The `lengthMin` rule checks if the field is at least a given length and that the field is a valid string.
```php
$v->rule('lengthMin', 'username', 5);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'martha']);
$v->rules([
'lengthMin' => [
['username', 5]
]
]);
$v->validate();
```
## lengthMax fields usage
The `lengthMax` rule checks if the field is at most a given length and that the field is a valid string.
```php
$v->rule('lengthMax', 'username', 10);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'bruins91']);
$v->rules([
'lengthMax' => [
['username', 10]
]
]);
$v->validate();
```
## min fields usage
The `min` rule checks if the field is at least a given value and that the provided value is numeric.
```php
$v->rule('min', 'age', 18);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['age' => 28]);
$v->rules([
'min' => [
['age', 18]
]
]);
$v->validate();
```
## max fields usage
The `max` rule checks if the field is at most a given value and that the provided value is numeric.
```php
$v->rule('max', 'age', 12);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['age' => 10]);
$v->rules([
'max' => [
['age', 12]
]
]);
$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
The `in` rule checks that the field is present in a given array of values.
```php
$v->rule('in', 'color', ['blue', 'green', 'red', 'purple']);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['color' => 'purple']);
$v->rules([
'in' => [
['color', ['blue', 'green', 'red', 'purple']]
]
]);
$v->validate();
```
## notIn fields usage
The `notIn` rule checks that the field is NOT present in a given array of values.
```php
$v->rule('notIn', 'color', ['blue', 'green', 'red', 'yellow']);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['color' => 'purple']);
$v->rules([
'notIn' => [
['color', ['blue', 'green', 'red', 'yellow']]
]
]);
$v->validate();
```
## ip fields usage
The `ip` rule checks that the field is a valid ip address. This includes IPv4, IPv6, private, and reserved ranges.
```php
$v->rule('ip', 'user_ip');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['user_ip' => '127.0.0.1']);
$v->rules([
'ip' => [
['user_ip']
]
]);
$v->validate();
```
## ipv4 fields usage
The `ipv4` rule checks that the field is a valid IPv4 address.
```php
$v->rule('ipv4', 'user_ip');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['user_ip' => '127.0.0.1']);
$v->rules([
'ipv4' => [
['user_ip']
]
]);
$v->validate();
```
## ipv6 fields usage
The `ipv6` rule checks that the field is a valid IPv6 address.
```php
$v->rule('ipv6', 'user_ip');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['user_ip' => '0:0:0:0:0:0:0:1']);
$v->rules([
'ipv6' => [
['user_ip']
]
]);
$v->validate();
```
## email fields usage
The `email` rule checks that the field is a valid email address.
```php
$v->rule('email', 'user_email');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['user_email' => 'someone@example.com']);
$v->rules([
'email' => [
['user_email']
]
]);
$v->validate();
```
## emailDNS fields usage
The `emailDNS` rule validates the field is a valid email address with an active DNS record or any type.
```php
$v->rule('emailDNS', 'user_email');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['user_email' => 'some_fake_email_address@gmail.com']);
$v->rules([
'emailDNS' => [
['user_email']
]
]);
$v->validate();
```
## url fields usage
The `url` rule checks the field is a valid url.
```php
$v->rule('url', 'website');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['website' => 'https://example.com/contact']);
$v->rules([
'url' => [
['website']
]
]);
$v->validate();
```
## urlActive fields usage
The `urlActive` rule checks the field is a valid url with an active A, AAAA, or CNAME record.
```php
$v->rule('urlActive', 'website');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['website' => 'https://example.com/contact']);
$v->rules([
'urlActive' => [
['website']
]
]);
$v->validate();
```
## alpha fields usage
The `alpha` rule checks the field is alphabetic characters only.
```php
$v->rule('alpha', 'username');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'batman']);
$v->rules([
'alpha' => [
['username']
]
]);
$v->validate();
```
## alphaNum fields usage
The `alphaNum` rule checks the field contains only alphabetic or numeric characters.
```php
$v->rule('alphaNum', 'username');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'batman123']);
$v->rules([
'alphaNum' => [
['username']
]
]);
$v->validate();
```
## ascii fields usage
The `ascii` rule checks the field contains only characters in the ascii character set.
```php
$v->rule('ascii', 'username');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'batman123']);
$v->rules([
'ascii' => [
['username']
]
]);
$v->validate();
```
## slug fields usage
The `slug` rule checks that the field only contains URL slug characters (a-z, 0-9, -, _).
```php
$v->rule('slug', 'username');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'L337-H4ckZ0rz_123']);
$v->rules([
'slug' => [
['username']
]
]);
$v->validate();
```
## regex fields usage
The `regex` rule ensures the field matches a given regex pattern.
(This regex checks the string is alpha numeric between 5-10 characters).
```php
$v->rule('regex', 'username', '/^[a-zA-Z0-9]{5,10}$/');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'Batman123']);
$v->rules([
'regex' => [
['username', '/^[a-zA-Z0-9]{5,10}$/']
]
]);
$v->validate();
```
## date fields usage
The `date` rule checks if the supplied field is a valid \DateTime object or if the string can be converted to a unix timestamp via strtotime().
```php
$v->rule('date', 'created_at');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['created_at' => '2018-10-13']);
$v->rules([
'date' => [
['created_at']
]
]);
$v->validate();
```
## dateFormat fields usage
The `dateFormat` rule checks that the supplied field is a valid date in a specified date format.
```php
$v->rule('dateFormat', 'created_at', 'Y-m-d');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['created_at' => '2018-10-13']);
$v->rules([
'dateFormat' => [
['created_at', 'Y-m-d']
]
]);
$v->validate();
```
## dateBefore fields usage
The `dateBefore` rule checks that the supplied field is a valid date before a specified date.
```php
$v->rule('dateBefore', 'created_at', '2018-10-13');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['created_at' => '2018-09-01']);
$v->rules([
'dateBefore' => [
['created_at', '2018-10-13']
]
]);
$v->validate();
```
## dateAfter fields usage
The `dateAfter` rule checks that the supplied field is a valid date after a specified date.
```php
$v->rule('dateAfter', 'created_at', '2018-10-13');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['created_at' => '2018-09-01']);
$v->rules([
'dateAfter' => [
['created_at', '2018-01-01']
]
]);
$v->validate();
```
## contains fields usage
The `contains` rule checks that a given string exists within the field and checks that the field and the search value are both valid strings.
```php
$v->rule('contains', 'username', 'man');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['username' => 'Batman123']);
$v->rules([
'contains' => [
['username', 'man']
]
]);
$v->validate();
```
*Note* You can use the optional strict flag to ensure a case-sensitive match.
The following example will return true:
```php
$v = new Valitron\Validator(['username' => 'Batman123']);
$v->rules([
'contains' => [
['username', 'man']
]
]);
$v->validate();
```
Whereas, this would return false, as the M in the search string is not uppercase in the provided value:
```php
$v = new Valitron\Validator(['username' => 'Batman123']);
$v->rules([
'contains' => [
['username', 'Man', true]
]
]);
$v->validate();
```
## subset fields usage
The `subset` rule checks that the field is either a scalar or array field and that all of it's values are contained within a given set of values.
```php
$v->rule('subset', 'colors', ['green', 'blue', 'orange']);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['colors' => ['green', 'blue']]);
$v->rules([
'subset' => [
['colors', ['orange', 'green', 'blue', 'red']]
]
]);
$v->validate();
```
This example would return false, as the provided color, purple, does not exist in the array of accepted values we're providing.
```php
$v = new Valitron\Validator(['colors' => ['purple', 'blue']]);
$v->rules([
'subset' => [
['colors', ['orange', 'green', 'blue', 'red']]
]
]);
$v->validate();
```
## containsUnique fields usage
The `containsUnique` rule checks that the provided field is an array and that all values contained within are unique, i.e. no duplicate values in the array.
```php
$v->rule('containsUnique', 'colors');
```
Alternate syntax.
```php
$v = new Valitron\Validator(['colors' => ['purple', 'blue']]);
$v->rules([
'containsUnique' => [
['colors']
]
]);
$v->validate();
```
This example would return false, as the values in the provided array are duplicates.
```php
$v = new Valitron\Validator(['colors' => ['purple', 'purple']]);
$v->rules([
'containsUnique' => [
['colors']
]
]);
$v->validate();
```
## Credit Card Validation usage
Credit card validation currently allows you to validate a Visa `visa`,
@@ -199,6 +1045,85 @@ $v->rule('creditCard', 'credit_card', $cardType, ['visa', 'mastercard']);
$v->validate(); // false
```
## instanceOf fields usage
The `instanceOf` rule checks that the field is an instance of a given class.
```php
$v->rule('instanceOf', 'date', \DateTime);
```
Alternate syntax.
```php
$v = new Valitron\Validator(['date' => new \DateTime()]);
$v->rules([
'instanceOf' => [
['date', 'DateTime']
]
]);
$v->validate();
```
*Note* You can also compare the value against a given object as opposed to the string class name.
This example would also return true:
```php
$v = new Valitron\Validator(['date' => new \DateTime()]);
$existingDateObject = new \DateTime();
$v->rules([
'instanceOf' => [
['date', $existingDateObject]
]
]);
$v->validate();
```
## optional fields usage
The `optional` rule ensures that if the field is present in the data set that it passes all validation rules.
```php
$v->rule('optional', 'username');
```
Alternate syntax.
This example would return true either when the 'username' field is not present or in the case where the username is only alphabetic characters.
```php
$v = new Valitron\Validator(['username' => 'batman']);
$v->rules([
'alpha' => [
['username']
],
'optional' => [
['username']
]
]);
$v->validate();
```
This example would return false, as although the field is optional, since it is provided it must pass all the validation rules, which in this case it does not.
```php
$v = new Valitron\Validator(['username' => 'batman123']);
$v->rules([
'alpha' => [
['username']
],
'optional' => [
['username']
]
]);
$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
@@ -214,7 +1139,7 @@ Valitron\Validator::addRule('alwaysFail', function($field, $value, array $params
```
You can also use one-off rules that are only valid for the specified
fields.
fields.
```php
$v = new Valitron\Validator(array("foo" => "bar"));
@@ -226,15 +1151,23 @@ $v->rule(function($field, $value, $params, $fields) {
This is useful because such rules can have access to variables
defined in the scope where the `Validator` lives. The Closure's
signature is identical to `Validator::addRule` callback's
signature.
signature.
If you wish to add your own rules that are not static (i.e.,
your rule is not static and available to call `Validator`
instances), you need to use `Validator::addInstanceRule`.
This rule will take the same parameters as
your rule is not static and available to call `Validator`
instances), you need to use `Validator::addInstanceRule`.
This rule will take the same parameters as
`Validator::addRule` but it has to be called on a `Validator`
instance.
## Chaining rules
You can chain multiple rules together using the following syntax.
```php
$v = new Valitron\Validator(['email_address' => 'test@test.com']);
$v->rule('required', 'email_address')->rule('email', 'email_address');
$v->validate();
```
## Alternate syntax for adding rules
@@ -303,7 +1236,7 @@ You can also add rules on a per-field basis:
$rules = [
'required',
['lengthMin', 4]
];
];
$v = new Valitron\Validator(array('foo' => 'bar'));
$v->mapFieldRules('foo', $rules);
@@ -391,4 +1324,3 @@ before running the tests:
6. Push to the branch (`git push origin my-new-feature`)
7. Create new Pull Request
8. Pat yourself on the back for being so awesome
+2 -2
View File
@@ -4,8 +4,8 @@
"description": "Simple, elegant, stand-alone validation library with NO dependencies",
"keywords": ["validation", "validator", "valid"],
"homepage": "http://github.com/vlucas/valitron",
"license" : "BSD-3-Clause",
"authors" : [
"license": "BSD-3-Clause",
"authors": [
{
"name": "Vance Lucas",
"email": "vance@vancelucas.com",
+1
View File
@@ -11,6 +11,7 @@ return array(
'min' => "يجب ان يكون اعلي من %s",
'max' => "يجب ان يكون اقل من %s",
'in' => "الُمدخل يغير صحيح",
'listContains' => "الُمدخل يغير صحيح",
'notIn' => "الُمدخل يغير صحيح",
'ip' => "رقم الإتصال غير صحيح",
'email' => "البريد الألكتروني غير صحيح",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "%d qədər uzunluğu olmalıdır",
'min' => "minimum %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",
'notIn' => "yalnış dəyər ehtiva edir",
'ip' => "düzgün IP ünvanı deyil",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "трябва да бъде %d символа дълго",
'min' => "трябвя да бъде поне %s",
'max' => "трябва да бъде не повече от %s",
'listContains' => "съдържа невалидна стойност",
'in' => "съдържа невалидна стойност",
'notIn' => "съдържа невалидна стойност",
'ip' => "е невалиден IP адрес",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "kann nicht länger als %d sein",
'min' => "muss größer als %s sein",
'max' => "muss kleiner als %s sein",
'listContains' => "enthält einen ungültigen Wert",
'in' => "enthält einen ungültigen Wert",
'notIn' => "enthält einen ungültigen Wert",
'ip' => "enthält keine gültige IP-Addresse",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "πρέπει να είναι μεγαλύτερο από %d",
'min' => "πρέπει να είναι τουλάχιστον %s",
'max' => "δεν πρέπει να είναι περισσότερο από %s",
'listContains' => "περιέχει μη έγκυρη τιμή",
'in' => "περιέχει μη έγκυρη τιμή",
'notIn' => "περιέχει μη έγκυρη τιμή",
'ip' => "δεν είναι έγκυρη διεύθυνση IP",
+38 -30
View File
@@ -1,34 +1,42 @@
<?php
return array(
'required' => "is required",
'equals' => "must be the same as '%s'",
'different' => "must be different than '%s'",
'accepted' => "must be accepted",
'numeric' => "must be numeric",
'integer' => "must be an integer",
'length' => "must be %d characters long",
'min' => "must be at least %s",
'max' => "must be no more than %s",
'in' => "contains invalid value",
'notIn' => "contains invalid value",
'ip' => "is not a valid IP address",
'email' => "is not a valid email address",
'url' => "is not a valid URL",
'urlActive' => "must be an active domain",
'alpha' => "must contain only letters a-z",
'alphaNum' => "must contain only letters a-z and/or numbers 0-9",
'slug' => "must contain only letters a-z, numbers 0-9, dashes and underscores",
'regex' => "contains invalid characters",
'date' => "is not a valid date",
'dateFormat' => "must be date with format '%s'",
'dateBefore' => "must be date before '%s'",
'dateAfter' => "must be date after '%s'",
'contains' => "must contain %s",
'boolean' => "must be a boolean",
'lengthBetween' => "must be between %d and %d characters",
'creditCard' => "must be a valid credit card number",
'lengthMin' => "must be at least %d characters long",
'lengthMax' => "must not exceed %d characters",
'instanceOf' => "must be an instance of '%s'"
'required' => "is required",
'equals' => "must be the same as '%s'",
'different' => "must be different than '%s'",
'accepted' => "must be accepted",
'numeric' => "must be numeric",
'integer' => "must be an integer",
'length' => "must be %d characters long",
'min' => "must be at least %s",
'max' => "must be no more than %s",
'listContains' => "contains invalid value",
'in' => "contains invalid value",
'notIn' => "contains invalid value",
'ip' => "is not a valid IP address",
'ipv4' => "is not a valid IPv4 address",
'ipv6' => "is not a valid IPv6 address",
'email' => "is not a valid email address",
'url' => "is not a valid URL",
'urlActive' => "must be an active domain",
'alpha' => "must contain only letters a-z",
'alphaNum' => "must contain only letters a-z and/or numbers 0-9",
'slug' => "must contain only letters a-z, numbers 0-9, dashes and underscores",
'regex' => "contains invalid characters",
'date' => "is not a valid date",
'dateFormat' => "must be date with format '%s'",
'dateBefore' => "must be date before '%s'",
'dateAfter' => "must be date after '%s'",
'contains' => "must contain %s",
'boolean' => "must be a boolean",
'lengthBetween' => "must be between %d and %d characters",
'creditCard' => "must be a valid credit card number",
'lengthMin' => "must be at least %d characters long",
'lengthMax' => "must not exceed %d characters",
'instanceOf' => "must be an instance of '%s'",
'containsUnique' => "must contain unique elements only",
'requiredWith' => "is required",
'requiredWithout'=> "is required",
'subset' => "contains an item that is not in the list",
'arrayHasKeys' => "does not contain all required keys",
);
+33 -30
View File
@@ -1,34 +1,37 @@
<?php
return array(
'required' => "es obligatorio",
'equals' => "debe ser igual a '%s'",
'different' => "debe ser diferente a '%s'",
'accepted' => "debe ser aceptado",
'numeric' => "debe ser numérico",
'integer' => "debe ser un entero",
'length' => "debe ser mas largo de %d",
'min' => "debe ser mayor de %s",
'max' => "debe ser menor de %s",
'in' => "contiene un valor inválido",
'notIn' => "contiene un valor inválido",
'ip' => "no es una dirección IP",
'email' => "no es un correo electrónico válido",
'url' => "no es una URL",
'urlActive' => "debe ser un dominio activo",
'alpha' => "debe contener solo letras a-z",
'alphaNum' => "debe contener solo letras a-z o números 0-9",
'slug' => "debe contener solo letras a-z, números 0-9, barras y guiones bajos",
'regex' => "contiene caracteres inválidos",
'date' => "no es una fecha válida",
'dateFormat' => "debe ser una fecha con formato '%s'",
'dateBefore' => "debe ser una fecha antes de '%s'",
'dateAfter' => "debe ser una fecha después de '%s'",
'contains' => "debe contener %s",
'boolean' => "debe ser booleano",
'lengthBetween' => "debe tener entre %d y %d caracteres",
'creditCard' => "debe ser un numero de tarjeta de crédito válido",
"lengthMin" => "debe tener al menos %d caracteres",
"lengthMax" => "debe tener menos de %d caracteres",
"instanceOf" => "debe ser una instancia de '%s'"
'required' => "es obligatorio",
'equals' => "debe ser igual a '%s'",
'different' => "debe ser diferente a '%s'",
'accepted' => "debe ser aceptado",
'numeric' => "debe ser numérico",
'integer' => "debe ser un entero",
'length' => "debe ser mas largo de %d",
'min' => "debe ser mayor de %s",
'max' => "debe ser menor de %s",
'in' => "contiene un valor inválido",
'notIn' => "contiene un valor inválido",
'ip' => "no es una dirección IP",
'email' => "no es un correo electrónico válido",
'url' => "no es una URL",
'urlActive' => "debe ser un dominio activo",
'alpha' => "debe contener solo letras a-z",
'alphaNum' => "debe contener solo letras a-z o números 0-9",
'slug' => "debe contener solo letras a-z, números 0-9, barras y guiones bajos",
'regex' => "contiene caracteres inválidos",
'date' => "no es una fecha válida",
'dateFormat' => "debe ser una fecha con formato '%s'",
'dateBefore' => "debe ser una fecha antes de '%s'",
'dateAfter' => "debe ser una fecha después de '%s'",
'contains' => "debe contener %s",
'boolean' => "debe ser booleano",
'lengthBetween' => "debe tener entre %d y %d caracteres",
'creditCard' => "debe ser un numero de tarjeta de crédito válido",
"lengthMin" => "debe tener al menos %d caracteres",
"lengthMax" => "debe tener menos de %d caracteres",
"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"
);
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "on lyhyempi kuin %d",
'min' => "ei ole vähintään %s",
'max' => "ei ole enintään %s",
'listContains' => "sisältää virheellisen arvon",
'in' => "sisältää virheellisen arvon",
'notIn' => "sisältää virheellisen arvon",
'ip' => "ei ole oikeanmuotoinen IP-osoite",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "doit être plus long que %d",
'min' => "doit être plus grand que %s",
'max' => "doit être plus petit que %s",
'listContains' => "contient une valeur non valide",
'in' => "contient une valeur non valide",
'notIn' => "contient une valeur non valide",
'ip' => "n'est pas une adresse IP valide",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "harus lebih panjang dari %d",
'min' => "harus lebih besar dari %s",
'max' => "harus kurang dari %s",
'listContains' => "berisi nilai/value yang tidak valid",
'in' => "berisi nilai/value yang tidak valid",
'notIn' => "berisi nilai/value yang tidak valid",
'ip' => "format alamat IP tidak benar",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "deve avere una lunghezza di %d",
'min' => "deve essere superiore a %s",
'max' => "deve essere inferiore a %s",
'listContains' => "contiene un valore non valido",
'in' => "contiene un valore non valido",
'notIn' => "contiene un valore non valido",
'ip' => "non è un indirizzo IP valido",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "は%d文字で入力してください",
'min' => "には%sより大きな値を入力してください",
'max' => "には%sより小さな値を入力してください",
'listContains' => "には選択できない値が含まれています",
'in' => "には選択できない値が含まれています",
'notIn' => "には選択できない値が含まれています",
'ip' => "はIPアドレスの書式として正しくありません",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "의 길이는 %d 이어야 합니다.",
'min' => "은(는) %s 이상이어야 합니다.",
'max' => "은(는) %s 이하여야 합니다.",
'listContains' => "은(는) 올바르지 않은 값을 포함하고 있습니다.",
'in' => "은(는) 올바르지 않은 값을 포함하고 있습니다.",
'notIn' => "은(는) 올바르지 않은 값을 포함하고 있습니다.",
'ip' => "은(는) 올바르지 않은 IP입니다.",
+6 -1
View File
@@ -9,9 +9,12 @@ return array(
'length' => "turi būti %d ženklų ilgio",
'min' => "turi būti bent %s",
'max' => "turi būti ne daugiau kaip %s",
'listContains' => "turi neteisingą vertę",
'in' => "turi neteisingą vertę",
'notIn' => "turi neteisingą vertę",
'ip' => "nėra teisingas IP adresas",
'ipv4' => "nėra teisingas IPv4 adresas",
'ipv6' => "nėra teisingas IPv6 adresas",
'email' => "nėra teisingas el. pašto adresas",
'url' => "nėra teisingas URL",
'urlActive' => "turi būti aktyvus domenas",
@@ -29,5 +32,7 @@ return array(
'creditCard' => "turi būti teisingas kreditinės kortelės numeris",
'lengthMin' => "turi būti bent %d ženklų ilgio",
'lengthMax' => "turi būti ne ilgesnis nei %d ženklų",
'instanceOf' => "turi būti „%s“ atvejis"
'instanceOf' => "turi būti „%s“ atvejis",
'containsUnique' => "turi turėti tik unikalius elementus",
'subset' => "turi elementą, kurio nėra sąraše"
);
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "nedrīkst būt garāks par %d simboliem",
'min' => "jābūt garā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",
'notIn' => "lauks satur nederīgu vērtību",
'ip' => " lauks nav derīga IP adrese",
+39
View File
@@ -0,0 +1,39 @@
<?php
// Norwegian Bokmål (nb)
return array(
'required' => "er påkrevd",
'equals' => "må være lik '%s'",
'different' => "må være annerledes enn '%s'",
'accepted' => "må aksepteres",
'numeric' => "må være numerisk",
'integer' => "må være et heltall",
'length' => "må være %d tegn langt",
'min' => "må være minst %s",
'max' => "må ikke være mer enn %s",
'listContains' => "inneholder ugyldig verdi",
'in' => "inneholder ugyldig verdi",
'notIn' => "inneholder ugyldig verdi",
'ip' => "er ikke en gyldig IP adresse",
'ipv4' => "er ikke en gyldig IPv4 adresse",
'ipv6' => "er ikke en gyldig IPv6 adresse",
'email' => "er ikke en gyldig e-postadresse",
'url' => "er ikke en gyldig URL",
'urlActive' => "må være et aktivt domene",
'alpha' => "må bare innholde bokstaver a-z",
'alphaNum' => "må bare innholde bokstaver a-z og/eller tall 0-9",
'slug' => "må bare innholde bokstaver a-z og/eller tall 0-9, bindestreker og understreker",
'regex' => "inneholder ulovlige tegn",
'date' => "er ikke en gyldig dato",
'dateFormat' => "må være en dato med format '%s'",
'dateBefore' => "må være en dato før '%s'",
'dateAfter' => "må være en dato etter '%s'",
'contains' => "må inneholde %s",
'boolean' => "må være en boolsk verdi",
'lengthBetween' => "må være mellom %d og %d tegn",
'creditCard' => "må være et gyldig kredittkortnummer",
'lengthMin' => "må være minst %d tegn langt",
'lengthMax' => "må ikke overstige %d tegn",
'instanceOf' => "må være en instans av '%s'",
'containsUnique'=> "må inneholde kun unike elementer",
'subset' => "inneholder et element som ikke er i listen"
);
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "moet minstens %d karakters lang zijn",
'min' => "moet minstens %s zijn",
'max' => "mag niet meer zijn dan %s",
'listContains' => "bevat een ongeldige waarde",
'in' => "bevat een ongeldige waarde",
'notIn' => "bevat een ongeldige waarde",
'ip' => "is geen geldig IP-adres",
+35
View File
@@ -0,0 +1,35 @@
<?php
return array(
'required' => "er nødvendig",
'equals' => "må være de samme som '%s'",
'different' => "må være annerledes enn '%s'",
'accepted' => "må aksepteres",
'numeric' => "må være numerisk",
'integer' => "må være et heltall",
'length' => "må være %d tegn",
'min' => "må være minst %s",
'max' => "må ikke være mer enn %s",
'listContains' => "inneholder ugyldig verdi",
'in' => "inneholder ugyldig verdi",
'notIn' => "inneholder ugyldig verdi",
'ip' => "er ikkje ein gyldig IP Adresse",
'email' => "er ikkje ein gyldig E-post adresse",
'url' => "er ikkje ein gyldig URL",
'urlActive' => "må være eit aktivt domene",
'alpha' => "må bare innholde bokstaver a-z",
'alphaNum' => "må bare innholde bokstaver a-z og/eller tall 0-9",
'slug' => "må bare innholde bokstaver a-z og/eller tall 0-9, bindestreker og understreker",
'regex' => "inneholder ulovlige tegn",
'date' => "er ikkje ein gylid dato",
'dateFormat' => "må være ein dato med formatet '%s'",
'dateBefore' => "må være ein dato før '%s'",
'dateAfter' => "må være ein dato etter '%s'",
'contains' => "må inneholde %s",
'boolean' => "må være ein boolsk verdi",
'lengthBetween' => "må være imellom %d og %d tegn",
'creditCard' => "må være et gyldig kredittkortnummer",
'lengthMin' => "må være minst %d tegn",
'lengthMax' => "må ikkje overstige %d tegn",
'instanceOf' => "må være ein instans av '%s'"
);
+1 -32
View File
@@ -1,34 +1,3 @@
<?php
return array(
'required' => "er nødvendig",
'equals' => "må være de samme som '%s'",
'different' => "må være annerledes enn '%s'",
'accepted' => "må aksepteres",
'numeric' => "må være numerisk",
'integer' => "må være et heltall",
'length' => "må være %d tegn",
'min' => "må være minst %s",
'max' => "må ikke være mer enn %s",
'in' => "inneholder ugyldig verdi",
'notIn' => "inneholder ugyldig verdi",
'ip' => "er ikkje ein gyldig IP Adresse",
'email' => "er ikkje ein gyldig E-post adresse",
'url' => "er ikkje ein gyldig URL",
'urlActive' => "må være eit aktivt domene",
'alpha' => "må bare innholde bokstaver a-z",
'alphaNum' => "må bare innholde bokstaver a-z og/eller tall 0-9",
'slug' => "må bare innholde bokstaver a-z og/eller tall 0-9, bindestreker og understreker",
'regex' => "inneholder ulovlige tegn",
'date' => "er ikkje ein gylid dato",
'dateFormat' => "må være ein dato med formatet '%s'",
'dateBefore' => "må være ein dato før '%s'",
'dateAfter' => "må være ein dato etter '%s'",
'contains' => "må inneholde %s",
'boolean' => "må være ein boolsk verdi",
'lengthBetween' => "må være imellom %d og %d tegn",
'creditCard' => "må være et gyldig kredittkortnummer",
'lengthMin' => "må være minst %d tegn",
'lengthMax' => "må ikkje overstige %d tegn",
'instanceOf' => "må være ein instans av '%s'"
);
return include __DIR__ . '/nn.php';
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "musi być dłuższe niż %d",
'min' => "musi być przynajmniej %s",
'max' => "nie może być większe niż %s",
'listContains' => "zawiera nieprawidłową wartość",
'in' => "zawiera nieprawidłową wartość",
'notIn' => "zawiera nieprawidłową wartość",
'ip' => "nie jest prawidłowym adresem IP",
+34 -31
View File
@@ -1,34 +1,37 @@
<?php
return array(
'required' => "é obrigatório",
'equals' => "deve ser o mesmo que '%s'",
'different' => "deve ser diferente de '%s'",
'accepted' => "deve ser aceito",
'numeric' => "deve ser um número",
'integer' => "deve ser um inteiro",
'length' => "deve ter %d caracteres",
'min' => "deve ser maior que %s",
'max' => "deve ser menor que %s",
'in' => "contém um valor inválido",
'notIn' => "contém um valor inválido",
'ip' => "não é um IP válido",
'email' => "não é um email válido",
'url' => "não é uma URL válida",
'urlActive' => "deve ser um domínio ativo",
'alpha' => "deve conter as letras a-z",
'alphaNum' => "deve conter apenas letras a-z e/ou números 0-9",
'slug' => "deve conter apenas letras a-z, números 0-9, ou os caracteres - ou _",
'regex' => "contém caracteres inválidos",
'date' => "não é uma data válida",
'dateFormat' => "deve ser uma data no formato '%s'",
'dateBefore' => "deve ser uma data anterior a '%s'",
'dateAfter' => "deve ser uma data posterior a '%s'",
'contains' => "deve conter %s",
'boolean' => "deve ser um booleano",
'lengthBetween' => "deve estar entre %d e %d caracteres",
'creditCard' => "deve ser um numero de cartão de credito válido",
'lengthMin' => "deve ter ao menos %d caracteres",
'lengthMax' => "não deve exceder %d caracteres",
'instanceOf' => "deve ser uma instância de '%s'"
);
'required' => "é obrigatório",
'equals' => "deve ser o mesmo que '%s'",
'different' => "deve ser diferente de '%s'",
'accepted' => "deve ser aceito",
'numeric' => "deve ser um número",
'integer' => "deve ser um inteiro",
'length' => "deve ter %d caracteres",
'min' => "deve ser maior que %s",
'max' => "deve ser menor que %s",
'in' => "contém um valor inválido",
'notIn' => "contém um valor inválido",
'ip' => "não é um IP válido",
'email' => "não é um email válido",
'url' => "não é uma URL válida",
'urlActive' => "deve ser um domínio ativo",
'alpha' => "deve conter as letras a-z",
'alphaNum' => "deve conter apenas letras a-z e/ou números 0-9",
'slug' => "deve conter apenas letras a-z, números 0-9, ou os caracteres - ou _",
'regex' => "contém caracteres inválidos",
'date' => "não é uma data válida",
'dateFormat' => "deve ser uma data no formato '%s'",
'dateBefore' => "deve ser uma data anterior a '%s'",
'dateAfter' => "deve ser uma data posterior a '%s'",
'contains' => "deve conter %s",
'boolean' => "deve ser um booleano",
'lengthBetween' => "deve estar entre %d e %d caracteres",
'creditCard' => "deve ser um numero de cartão de credito válido",
'lengthMin' => "deve ter ao menos %d caracteres",
'lengthMax' => "não deve exceder %d caracteres",
'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"
);
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "trebuie sa fie mai lung decat %d",
'min' => "trebuie sa fie cel putin %s",
'max' => "nu trebuie sa fie mai mult de %s",
'listContains' => "contine caractere invalide",
'in' => "contine caractere invalide",
'notIn' => "contine o valoare invalida",
'ip' => "nu este o adresa IP valida",
+35 -30
View File
@@ -1,34 +1,39 @@
<?php
return array(
'required' => "обязательно для заполнения",
'equals' => "должно содержать '%s'",
'different' => "должно отличаться от '%s'",
'accepted' => "должно быть указано",
'numeric' => "должно содержать числовое значение",
'integer' => "должно быть числом",
'length' => "должно быть длиннее, чем %d",
'min' => "должно быть больше, чем %s",
'max' => "должно быть меньше, чем %s",
'in' => "содержит неверное значение",
'notIn' => "содержит неверное значение",
'ip' => "не является валидным IP адресом",
'email' => "не является валидным email адресом",
'url' => "не является валидной ссылкой",
'urlActive' => "содержит не активную ссылку",
'alpha' => "должно содержать только латинские символы",
'alphaNum' => "должно содержать только латинские символы и/или цифры",
'slug' => "должно содержать только латинские символы, цифры, тире и подчёркивания",
'regex' => "содержит недопустимые символы",
'date' => "не является датой",
'dateFormat' => "должно содержать дату следующего формата: %s",
'dateBefore' => "должно содержать дату не позднее, чем %s",
'dateAfter' => "должно содержать дату не ранее, чем %s",
'contains' => "должно содержать %s",
'boolean' => "должно содержать логическое значение",
'lengthBetween' => "должно содержать от %d до %d символов",
'creditCard' => "должно быть номером кредитной карты",
'lengthMin' => "должно содержать более %d символов",
'lengthMax' => "должно содержать менее %d символов",
'instanceOf' => "должно быть объектом класса '%s'"
'required' => "обязательно для заполнения",
'equals' => "должно совпадать со значением '%s'",
'different' => "должно отличаться от '%s'",
'accepted' => "должно быть указано",
'numeric' => "должно содержать числовое значение",
'integer' => "должно быть числом",
'length' => "должно быть длиннее, чем %d",
'min' => "должно быть не менее, чем %s",
'max' => "должно быть не более, чем %s",
'listContains' => "содержит неверное значение",
'in' => "содержит неверное значение",
'notIn' => "содержит неверное значение",
'ip' => "не является валидным IP адресом",
'ipv4' => "не является валидным IPv4 адресом",
'ipv6' => "не является валидным IPv6 адресом",
'email' => "не является валидным email адресом",
'url' => "не является валидной ссылкой",
'urlActive' => "содержит не активную ссылку",
'alpha' => "должно содержать только латинские символы",
'alphaNum' => "должно содержать только латинские символы и/или цифры",
'slug' => "должно содержать только латинские символы, цифры, тире и подчёркивания",
'regex' => "содержит недопустимые символы",
'date' => "не является датой",
'dateFormat' => "должно содержать дату следующего формата: %s",
'dateBefore' => "должно содержать дату не позднее, чем %s",
'dateAfter' => "должно содержать дату не ранее, чем %s",
'contains' => "должно содержать %s",
'boolean' => "должно содержать логическое значение",
'lengthBetween' => "должно содержать от %d до %d символов",
'creditCard' => "должно быть номером кредитной карты",
'lengthMin' => "должно содержать более %d символов",
'lengthMax' => "должно содержать менее %d символов",
'instanceOf' => "должно быть объектом класса '%s'",
'containsUnique' => "должно содержать только уникальные элементы",
'subset' => "содержит элемент, не указанный в списке",
);
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "musí byť dlhý aspoň %d",
'min' => "musí byť dlhý minimálne %s",
'max' => "musí byť maximálne %s",
'listContains' => "obsahuje nepovolenú hodnotu",
'in' => "obsahuje nepovolenú hodnotu",
'notIn' => "obsahuje nepovolenú hodnotu",
'ip' => "nie je korektná IP adresa",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "måste vara %d tecken långt",
'min' => "måste vara minst %s",
'max' => "får inte vara mer än %s",
'listContains' => "innehåller ogiltigt värde",
'in' => "innehåller ogiltigt värde",
'notIn' => "innehåller ogiltigt värde",
'ip' => "är inte en giltlig IP-adress",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "ต้องมีความยาวมากกว่า %d",
'min' => "ต้องมีอย่างน้อย %s",
'max' => "ต้องไม่มากเกิน %s",
'listContains' => "ประกอบด้วยค่าที่ไม่ถูกต้อง",
'in' => "ประกอบด้วยค่าที่ไม่ถูกต้อง",
'notIn' => "ประกอบด้วยค่าที่ไม่ถูกต้อง",
'ip' => "ไม่ใช่ IP ที่ถูกต้อง",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "en az %d adet uzunluğunda olmalı",
'min' => "en az böyle olmalı %s",
'max' => "bundan daha fazla olmalı %s",
'listContains' => "geçersiz değer içeriyor",
'in' => "geçersiz değer içeriyor",
'notIn' => "geçersiz değer içeriyor",
'ip' => "geçerli bir IP adresi değil",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "має бути довшим, ніж %d",
'min' => "має бути більше, ніж %s",
'max' => "повинно бути менше, ніж %s",
'listContains' => "містить невірне значення",
'in' => "містить невірне значення",
'notIn' => "містить невірне значення",
'ip' => "не є валідною IP адресою",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "phải dài hơn %d",
'min' => "ít nhất %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ệ",
'notIn' => "chứa giá trị không hợp lệ",
'ip' => "địa chỉ IP không hợp lệ",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "长度必须大于 %d",
'min' => "必须大于 %s",
'max' => "必须小于 %s",
'listContains' => "无效的值",
'in' => "无效的值",
'notIn' => "无效的值",
'ip' => "无效IP地址",
+1
View File
@@ -10,6 +10,7 @@ return array(
'length' => "長度必須大於 %d",
'min' => "必須大於 %s",
'max' => "必須小於 %s",
'listContains' => "無效的值",
'in' => "無效的值",
'notIn' => "無效的值",
'ip' => "無效IP地址",
+362 -149
View File
@@ -1,4 +1,5 @@
<?php
namespace Valitron;
/**
@@ -85,10 +86,10 @@ class Validator
/**
* Setup validation
*
* @param array $data
* @param array $fields
* @param string $lang
* @param string $langDir
* @param array $data
* @param array $fields
* @param string $lang
* @param string $langDir
* @throws \InvalidArgumentException
*/
public function __construct($data = array(), $fields = array(), $lang = null, $langDir = null)
@@ -105,7 +106,7 @@ class Validator
// Load language file in directory
$langFile = rtrim($langDir, '/') . '/' . $lang . '.php';
if (stream_resolve_include_path($langFile) ) {
if (stream_resolve_include_path($langFile)) {
$langMessages = include $langFile;
static::$_ruleMessages = array_merge(static::$_ruleMessages, $langMessages);
} else {
@@ -147,13 +148,13 @@ class Validator
* Required field validator
*
* @param string $field
* @param mixed $value
* @param array $params
* @param mixed $value
* @param array $params
* @return bool
*/
protected function validateRequired($field, $value, $params= array())
protected function validateRequired($field, $value, $params = array())
{
if (isset($params[0]) && (bool) $params[0]){
if (isset($params[0]) && (bool)$params[0]) {
$find = $this->getPart($this->_fields, explode('.', $field), true);
return $find[1];
}
@@ -173,7 +174,6 @@ class Validator
* @param string $field
* @param mixed $value
* @param array $params
* @internal param array $fields
* @return bool
*/
protected function validateEquals($field, $value, array $params)
@@ -189,7 +189,6 @@ class Validator
* @param string $field
* @param mixed $value
* @param array $params
* @internal param array $fields
* @return bool
*/
protected function validateDifferent($field, $value, array $params)
@@ -205,7 +204,7 @@ class Validator
* This validation rule implies the field is "required"
*
* @param string $field
* @param mixed $value
* @param mixed $value
* @return bool
*/
protected function validateAccepted($field, $value)
@@ -219,7 +218,7 @@ class Validator
* Validate that a field is an array
*
* @param string $field
* @param mixed $value
* @param mixed $value
* @return bool
*/
protected function validateArray($field, $value)
@@ -231,7 +230,7 @@ class Validator
* Validate that a field is numeric
*
* @param string $field
* @param mixed $value
* @param mixed $value
* @return bool
*/
protected function validateNumeric($field, $value)
@@ -243,13 +242,13 @@ class Validator
* Validate that a field is an integer
*
* @param string $field
* @param mixed $value
* @param array $params
* @param mixed $value
* @param array $params
* @return bool
*/
protected function validateInteger($field, $value, $params)
{
if (isset($params[0]) && (bool) $params[0]){
if (isset($params[0]) && (bool)$params[0]) {
//strict mode
return preg_match('/^([0-9]|-[1-9]|-?[1-9][0-9]*)$/i', $value);
}
@@ -263,7 +262,6 @@ class Validator
* @param string $field
* @param mixed $value
* @param array $params
* @internal param array $fields
* @return bool
*/
protected function validateLength($field, $value, $params)
@@ -283,7 +281,7 @@ class Validator
* @param string $field
* @param mixed $value
* @param array $params
* @return boolean
* @return bool
*/
protected function validateLengthBetween($field, $value, $params)
{
@@ -296,10 +294,10 @@ class Validator
* Validate the length of a string (min)
*
* @param string $field
* @param mixed $value
* @param array $params
* @param mixed $value
* @param array $params
*
* @return boolean
* @return bool
*/
protected function validateLengthMin($field, $value, $params)
{
@@ -312,10 +310,10 @@ class Validator
* Validate the length of a string (max)
*
* @param string $field
* @param mixed $value
* @param array $params
* @param mixed $value
* @param array $params
*
* @return boolean
* @return bool
*/
protected function validateLengthMax($field, $value, $params)
{
@@ -347,7 +345,6 @@ class Validator
* @param string $field
* @param mixed $value
* @param array $params
* @internal param array $fields
* @return bool
*/
protected function validateMin($field, $value, $params)
@@ -367,7 +364,6 @@ class Validator
* @param string $field
* @param mixed $value
* @param array $params
* @internal param array $fields
* @return bool
*/
protected function validateMax($field, $value, $params)
@@ -385,9 +381,8 @@ class Validator
* Validate the size of a field is between min and max values
*
* @param string $field
* @param mixed $value
* @param array $params
* @param mixed $value
* @param array $params
* @return bool
*/
protected function validateBetween($field, $value, $params)
@@ -410,7 +405,6 @@ class Validator
* @param string $field
* @param mixed $value
* @param array $params
* @internal param array $fields
* @return bool
*/
protected function validateIn($field, $value, $params)
@@ -428,13 +422,35 @@ class Validator
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)
{
$isAssoc = array_values($value) !== $value;
if ($isAssoc) {
$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
*
* @param string $field
* @param mixed $value
* @param array $params
* @internal param array $fields
* @return bool
*/
protected function validateNotIn($field, $value, $params)
@@ -446,7 +462,7 @@ class Validator
* Validate a field contains a given string
*
* @param string $field
* @param mixed $value
* @param string $value
* @param array $params
* @return bool
*/
@@ -461,10 +477,9 @@ class Validator
$strict = true;
if (isset($params[1])) {
$strict = (bool) $params[1];
$strict = (bool)$params[1];
}
$isContains = false;
if ($strict) {
if (function_exists('mb_strpos')) {
$isContains = mb_strpos($value, $params[0]) !== false;
@@ -481,11 +496,51 @@ class Validator
return $isContains;
}
/**
* Validate that all field values contains a given array
*
* @param string $field
* @param array $value
* @param array $params
* @return bool
*/
protected function validateSubset($field, $value, $params)
{
if (!isset($params[0])) {
return false;
}
if (!is_array($params[0])) {
$params[0] = array($params[0]);
}
if (is_scalar($value) || is_null($value)) {
return $this->validateIn($field, $value, $params);
}
$intersect = array_intersect($value, $params[0]);
return array_diff($value, $intersect) === array_diff($intersect, $value);
}
/**
* Validate that field array has only unique values
*
* @param string $field
* @param array $value
* @return bool
*/
protected function validateContainsUnique($field, $value)
{
if (!is_array($value)) {
return false;
}
return $value === array_unique($value, SORT_REGULAR);
}
/**
* Validate that a field is a valid IP address
*
* @param string $field
* @param mixed $value
* @param mixed $value
* @return bool
*/
protected function validateIp($field, $value)
@@ -494,22 +549,64 @@ class Validator
}
/**
* Validate that a field is a valid e-mail address
* Validate that a field is a valid IP v4 address
*
* @param string $field
* @param mixed $value
* @return bool
*/
protected function validateIpv4($field, $value)
{
return filter_var($value, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4) !== false;
}
/**
* Validate that a field is a valid IP v6 address
*
* @param string $field
* @param mixed $value
* @return bool
*/
protected function validateIpv6($field, $value)
{
return filter_var($value, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6) !== false;
}
/**
* Validate that a field is a valid e-mail address
*
* @param string $field
* @param mixed $value
* @return bool
*/
protected function validateEmail($field, $value)
{
return filter_var($value, \FILTER_VALIDATE_EMAIL) !== false;
}
/**
* Validate that a field contains only ASCII characters
*
* @param $field
* @param $value
* @return bool|false|string
*/
protected function validateAscii($field, $value)
{
// multibyte extension needed
if (function_exists('mb_detect_encoding')) {
return mb_detect_encoding($value, 'ASCII', true);
}
// fallback with regex
return 0 === preg_match('/[^\x00-\x7F]/', $value);
}
/**
* Validate that a field is a valid e-mail address and the domain name is active
*
* @param string $field
* @param mixed $value
* @param mixed $value
* @return bool
*/
protected function validateEmailDNS($field, $value)
@@ -529,7 +626,7 @@ class Validator
* Validate that a field is a valid URL by syntax
*
* @param string $field
* @param mixed $value
* @param mixed $value
* @return bool
*/
protected function validateUrl($field, $value)
@@ -547,7 +644,7 @@ class Validator
* Validate that a field is an active URL by verifying DNS record
*
* @param string $field
* @param mixed $value
* @param mixed $value
* @return bool
*/
protected function validateUrlActive($field, $value)
@@ -567,7 +664,7 @@ class Validator
* Validate that a field contains only alphabetic characters
*
* @param string $field
* @param mixed $value
* @param mixed $value
* @return bool
*/
protected function validateAlpha($field, $value)
@@ -579,7 +676,7 @@ class Validator
* Validate that a field contains only alpha-numeric characters
*
* @param string $field
* @param mixed $value
* @param mixed $value
* @return bool
*/
protected function validateAlphaNum($field, $value)
@@ -591,12 +688,12 @@ class Validator
* Validate that a field contains only alpha-numeric characters, dashes, and underscores
*
* @param string $field
* @param mixed $value
* @param mixed $value
* @return bool
*/
protected function validateSlug($field, $value)
{
if(is_array($value)) {
if (is_array($value)) {
return false;
}
return preg_match('/^([-a-z0-9_-])+$/i', $value);
@@ -606,8 +703,8 @@ class Validator
* Validate that a field passes a regular expression check
*
* @param string $field
* @param mixed $value
* @param array $params
* @param mixed $value
* @param array $params
* @return bool
*/
protected function validateRegex($field, $value, $params)
@@ -619,7 +716,7 @@ class Validator
* Validate that a field is a valid date
*
* @param string $field
* @param mixed $value
* @param mixed $value
* @return bool
*/
protected function validateDate($field, $value)
@@ -640,7 +737,6 @@ class Validator
* @param string $field
* @param mixed $value
* @param array $params
* @internal param array $fields
* @return bool
*/
protected function validateDateFormat($field, $value, $params)
@@ -656,7 +752,6 @@ class Validator
* @param string $field
* @param mixed $value
* @param array $params
* @internal param array $fields
* @return bool
*/
protected function validateDateBefore($field, $value, $params)
@@ -673,7 +768,6 @@ class Validator
* @param string $field
* @param mixed $value
* @param array $params
* @internal param array $fields
* @return bool
*/
protected function validateDateAfter($field, $value, $params)
@@ -688,7 +782,7 @@ class Validator
* Validate that a field contains a boolean.
*
* @param string $field
* @param mixed $value
* @param mixed $value
* @return bool
*/
protected function validateBoolean($field, $value)
@@ -701,8 +795,8 @@ class Validator
* optionally filtered by an array
*
* @param string $field
* @param mixed $value
* @param array $params
* @param mixed $value
* @param array $params
* @return bool
*/
protected function validateCreditCard($field, $value, $params)
@@ -718,7 +812,7 @@ class Validator
if (is_array($params[0])) {
$cards = $params[0];
} elseif (is_string($params[0])) {
$cardType = $params[0];
$cardType = $params[0];
if (isset($params[1]) && is_array($params[1])) {
$cards = $params[1];
if (!in_array($cardType, $cards)) {
@@ -741,7 +835,7 @@ class Validator
return false;
}
for ($i = 0; $i < $strlen; $i++) {
$digit = (int) substr($number, $strlen - $i - 1, 1);
$digit = (int)substr($number, $strlen - $i - 1, 1);
if ($i % 2 == 1) {
$sub_total = $digit * 2;
if ($sub_total > 9) {
@@ -753,7 +847,7 @@ class Validator
$sum += $sub_total;
}
if ($sum > 0 && $sum % 10 == 0) {
return true;
return true;
}
return false;
@@ -764,11 +858,11 @@ class Validator
return true;
} else {
$cardRegex = array(
'visa' => '#^4[0-9]{12}(?:[0-9]{3})?$#',
'mastercard' => '#^(5[1-5]|2[2-7])[0-9]{14}$#',
'amex' => '#^3[47][0-9]{13}$#',
'dinersclub' => '#^3(?:0[0-5]|[68][0-9])[0-9]{11}$#',
'discover' => '#^6(?:011|5[0-9]{2})[0-9]{12}$#',
'visa' => '#^4[0-9]{12}(?:[0-9]{3})?$#',
'mastercard' => '#^(5[1-5]|2[2-7])[0-9]{14}$#',
'amex' => '#^3[47][0-9]{13}$#',
'dinersclub' => '#^3(?:0[0-5]|[68][0-9])[0-9]{11}$#',
'discover' => '#^6(?:011|5[0-9]{2})[0-9]{12}$#',
);
if (isset($cardType)) {
@@ -826,14 +920,127 @@ class Validator
return $isInstanceOf;
}
//Validate optional field
protected function validateOptional($field, $value, $params) {
//Always 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 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
if (isset($fields[$requiredField]) && !is_null($fields[$requiredField])
&& (is_string($fields[$requiredField]) ? trim($fields[$requiredField]) !== '' : true)) {
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;
}
/**
* Get array of fields and data
* 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
if (!isset($fields[$requiredField]) || (is_null($fields[$requiredField])
|| (is_string($fields[$requiredField]) && trim($fields[$requiredField]) === ''))) {
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
*
* @param $field
* @param $value
* @param $params
* @return bool
*/
protected function validateOptional($field, $value, $params)
{
//Always 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
*
* @return array
*/
@@ -861,12 +1068,12 @@ class Validator
* Add an error to error messages array
*
* @param string $field
* @param string $msg
* @param string $message
* @param array $params
*/
public function error($field, $msg, array $params = array())
public function error($field, $message, array $params = array())
{
$msg = $this->checkAndSetLabel($field, $msg, $params);
$message = $this->checkAndSetLabel($field, $message, $params);
$values = array();
// Printed values need to be in string format
@@ -890,18 +1097,18 @@ class Validator
$values[] = $param;
}
$this->_errors[$field][] = vsprintf($msg, $values);
$this->_errors[$field][] = vsprintf($message, $values);
}
/**
* Specify validation message to use for error for the last validation rule
*
* @param string $msg
* @return $this
* @param string $message
* @return Validator
*/
public function message($msg)
public function message($message)
{
$this->_validations[count($this->_validations) - 1]['message'] = $msg;
$this->_validations[count($this->_validations) - 1]['message'] = $message;
return $this;
}
@@ -925,7 +1132,7 @@ class Validator
}
// Catches the case where the data isn't an array or object
if (is_scalar($data)) {
return array(NULL, false);
return array(null, false);
}
$identifier = array_shift($identifiers);
// Glob match
@@ -940,24 +1147,21 @@ class Validator
}
}
return array($values, true);
}
// Dead end, abort
elseif ($identifier === NULL || ! isset($data[$identifier])) {
} // Dead end, abort
elseif ($identifier === null || ! isset($data[$identifier])) {
if ($allow_empty){
//when empty values are allowed, we only care if the key exists
return array(null, array_key_exists($identifier, $data));
}
return array(null, false);
}
// Match array element
} // Match array element
elseif (count($identifiers) === 0) {
if ($allow_empty){
if ($allow_empty) {
//when empty values are allowed, we only care if the key exists
return array(null, array_key_exists($identifier, $data));
}
return array($data[$identifier], false);
}
// We need to go deeper
return array($data[$identifier], $allow_empty);
} // We need to go deeper
else {
return $this->getPart($data[$identifier], $identifiers, $allow_empty);
}
@@ -966,22 +1170,23 @@ class Validator
/**
* Run validations and return boolean result
*
* @return boolean
* @return bool
*/
public function validate()
{
$set_to_break = false;
$set_to_break = false;
foreach ($this->_validations as $v) {
foreach ($v['fields'] as $field) {
list($values, $multiple) = $this->getPart($this->_fields, explode('.', $field));
list($values, $multiple) = $this->getPart($this->_fields, explode('.', $field), false);
// Don't validate if the field is not required and the value is empty
if ($this->hasRule('optional', $field) && isset($values)) {
// Don't validate if the field is not required and the value is empty and we don't have a conditionally required rule present on the field
if (($this->hasRule('optional', $field) && isset($values))
|| ($this->hasRule('requiredWith', $field) || $this->hasRule('requiredWithout', $field))) {
//Continue with execution below if statement
} elseif (
$v['rule'] !== 'required' && !$this->hasRule('required', $field) &&
$v['rule'] !== 'accepted' &&
(! isset($values) || $values === '' || ($multiple && count($values) == 0))
(!isset($values) || $values === '' || ($multiple && count($values) == 0))
) {
continue;
}
@@ -996,6 +1201,8 @@ class Validator
if (!$multiple) {
$values = array($values);
} else if (! $this->hasRule('required', $field)){
$values = array_filter($values);
}
$result = true;
@@ -1005,13 +1212,15 @@ class Validator
if (!$result) {
$this->error($field, $v['message'], $v['params']);
if($this->stop_on_first_fail) {
$set_to_break = true;
break;
if ($this->stop_on_first_fail) {
$set_to_break = true;
break;
}
}
}
if($set_to_break) break;
if ($set_to_break) {
break;
}
}
return count($this->errors()) === 0;
@@ -1021,8 +1230,9 @@ class Validator
* Should the validation stop a rule is failed
* @param bool $stop
*/
public function stopOnFirstFail($stop = true) {
$this->stop_on_first_fail = (bool) $stop;
public function stopOnFirstFail($stop = true)
{
$this->stop_on_first_fail = (bool)$stop;
}
/**
@@ -1050,9 +1260,8 @@ class Validator
*
* @param string $name The name of the rule
* @param string $field The name of the field
* @return boolean
* @return bool
*/
protected function hasRule($name, $field)
{
foreach ($this->_validations as $validation) {
@@ -1069,18 +1278,19 @@ class Validator
protected static function assertRuleCallback($callback)
{
if (!is_callable($callback)) {
throw new \InvalidArgumentException('Second argument must be a valid callback. Given argument was not callable.');
throw new \InvalidArgumentException(
'Second argument must be a valid callback. Given argument was not callable.'
);
}
}
/**
* Adds a new validation rule callback that is tied to the current
* instance only.
*
* @param string $name
* @param mixed $callback
* @param string $message
* @param string $name
* @param callable $callback
* @param string $message
* @throws \InvalidArgumentException
*/
public function addInstanceRule($name, $callback, $message = null)
@@ -1094,15 +1304,14 @@ class Validator
/**
* Register new validation rule callback
*
* @param string $name
* @param mixed $callback
* @param string $message
* @param string $name
* @param callable $callback
* @param string $message
* @throws \InvalidArgumentException
*/
public static function addRule($name, $callback, $message = null)
{
if ($message === null)
{
if ($message === null) {
$message = static::ERROR_DEFAULT;
}
@@ -1112,18 +1321,20 @@ class Validator
static::$_ruleMessages[$name] = $message;
}
/**
* @param mixed $fields
* @return string
*/
public function getUniqueRuleName($fields)
{
if (is_array($fields))
{
if (is_array($fields)) {
$fields = implode("_", $fields);
}
$orgName = "{$fields}_rule";
$name = $orgName;
$rules = $this->getRules();
while (isset($rules[$name]))
{
while (isset($rules[$name])) {
$name = $orgName . "_" . rand(0, 10000);
}
@@ -1134,7 +1345,7 @@ class Validator
* Returns true if either a validator with the given name has been
* registered or there is a default validator by that name.
*
* @param string $name
* @param string $name
* @return bool
*/
public function hasValidator($name)
@@ -1147,9 +1358,9 @@ class Validator
/**
* Convenience method to add a single validation rule
*
* @param string|callback $rule
* @param array|string $fields
* @return $this
* @param string|callable $rule
* @param array|string $fields
* @return Validator
* @throws \InvalidArgumentException
*/
public function rule($rule, $fields)
@@ -1158,11 +1369,10 @@ class Validator
$params = array_slice(func_get_args(), 2);
if (is_callable($rule)
&& !(is_string($rule) && $this->hasValidator($rule)))
{
&& !(is_string($rule) && $this->hasValidator($rule))) {
$name = $this->getUniqueRuleName($fields);
$msg = isset($params[0]) ? $params[0] : null;
$this->addInstanceRule($name, $rule, $msg);
$message = isset($params[0]) ? $params[0] : null;
$this->addInstanceRule($name, $rule, $message);
$rule = $name;
}
@@ -1170,13 +1380,15 @@ class Validator
if (!isset($errors[$rule])) {
$ruleMethod = 'validate' . ucfirst($rule);
if (!method_exists($this, $ruleMethod)) {
throw new \InvalidArgumentException("Rule '" . $rule . "' has not been registered with " . __CLASS__ . "::addRule().");
throw new \InvalidArgumentException(
"Rule '" . $rule . "' has not been registered with " . get_called_class() . "::addRule()."
);
}
}
// Ensure rule has an accompanying message
$msgs = $this->getRuleMessages();
$message = isset($msgs[$rule]) ? $msgs[$rule] : self::ERROR_DEFAULT;
$messages = $this->getRuleMessages();
$message = isset($messages[$rule]) ? $messages[$rule] : self::ERROR_DEFAULT;
// Ensure message contains field label
if (function_exists('mb_strpos')) {
@@ -1190,8 +1402,8 @@ class Validator
$this->_validations[] = array(
'rule' => $rule,
'fields' => (array) $fields,
'params' => (array) $params,
'fields' => (array)$fields,
'params' => (array)$params,
'message' => $message
);
@@ -1202,8 +1414,7 @@ class Validator
* Add label to rule
*
* @param string $value
* @internal param array $labels
* @return $this
* @return Validator
*/
public function label($value)
{
@@ -1217,7 +1428,7 @@ class Validator
* Add labels to rules
*
* @param array $labels
* @return $this
* @return Validator
*/
public function labels($labels = array())
{
@@ -1228,29 +1439,29 @@ class Validator
/**
* @param string $field
* @param string $msg
* @param string $message
* @param array $params
* @return array
*/
protected function checkAndSetLabel($field, $msg, $params)
protected function checkAndSetLabel($field, $message, $params)
{
if (isset($this->_labels[$field])) {
$msg = str_replace('{field}', $this->_labels[$field], $msg);
$message = str_replace('{field}', $this->_labels[$field], $message);
if (is_array($params)) {
$i = 1;
foreach ($params as $k => $v) {
$tag = '{field'. $i .'}';
$tag = '{field' . $i . '}';
$label = isset($params[$k]) && (is_numeric($params[$k]) || is_string($params[$k])) && isset($this->_labels[$params[$k]]) ? $this->_labels[$params[$k]] : $tag;
$msg = str_replace($tag, $label, $msg);
$message = str_replace($tag, $label, $message);
$i++;
}
}
} else {
$msg = str_replace('{field}', ucwords(str_replace('_', ' ', $field)), $msg);
$message = str_replace('{field}', ucwords(str_replace('_', ' ', $field)), $message);
}
return $msg;
return $message;
}
/**
@@ -1263,8 +1474,8 @@ class Validator
foreach ($rules as $ruleType => $params) {
if (is_array($params)) {
foreach ($params as $innerParams) {
if (! is_array($innerParams)){
$innerParams = (array) $innerParams;
if (!is_array($innerParams)) {
$innerParams = (array)$innerParams;
}
array_unshift($innerParams, $ruleType);
call_user_func_array(array($this, 'rule'), $innerParams);
@@ -1280,7 +1491,7 @@ class Validator
*
* @param array $data
* @param array $fields
* @return \Valitron\Validator
* @return Validator
*/
public function withData($data, $fields = array())
{
@@ -1293,32 +1504,33 @@ class Validator
/**
* Convenience method to add validation rule(s) by field
*
* @param string field_name
* @param array $rules
* @param string $field
* @param array $rules
*/
public function mapFieldRules($field_name, $rules){
public function mapFieldRules($field, $rules)
{
$me = $this;
array_map(function($rule) use($field_name, $me){
array_map(function ($rule) use ($field, $me) {
//rule must be an array
$rule = (array)$rule;
//First element is the name of the rule
$rule_name = array_shift($rule);
$ruleName = array_shift($rule);
//find a custom message, if any
$message = null;
if (isset($rule['message'])){
if (isset($rule['message'])) {
$message = $rule['message'];
unset($rule['message']);
}
//Add the field and additional parameters to the rule
$added = call_user_func_array(array($me, 'rule'), array_merge(array($rule_name, $field_name), $rule));
if (! empty($message)){
$added = call_user_func_array(array($me, 'rule'), array_merge(array($ruleName, $field), $rule));
if (!empty($message)) {
$added->message($message);
}
}, (array) $rules);
}, (array)$rules);
}
/**
@@ -1326,10 +1538,11 @@ class Validator
*
* @param array $rules
*/
public function mapFieldsRules($rules){
public function mapFieldsRules($rules)
{
$me = $this;
array_map(function($field_name) use($rules, $me){
$me->mapFieldRules($field_name, $rules[$field_name]);
array_map(function ($field) use ($rules, $me) {
$me->mapFieldRules($field, $rules[$field]);
}, array_keys($rules));
}
}