Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple objects validation #41

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,44 @@ Array
)
*/
```
And you can also validate multiple identical objects into array using asterisk sign in this way:

```php
use Respect\Validation\Validator as v;

$app = new \Slim\App();

//Create the validators
$nameValidator = v::alnum()->length(1, 100);
$ageValidator = v::numeric()->between(0, 120);
$validators = array(
'people' => array(
'*' => array(
'name' => $nameValidator,
'age' => $ageValidator,
)
),
);
```

If you'll have an error in some of objects, the result would be like this where **2** is the index of the object into *people* array:

```php
//In your route
$errors = $req->getAttribute('errors');

print_r($errors);
/*
Array
(
[people.2.age] => Array
(
[0] => "180 must be less than or equal to 120"
)

)
*/
```

### XML requests

Expand Down
12 changes: 11 additions & 1 deletion src/Validation.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,17 @@ private function validate($params = [], $validators = [], $actualKeys = [])
$actualKeys[] = $key;
$param = $this->getNestedParam($params, $actualKeys);
if (is_array($validator)) {
$this->validate($params, $validator, $actualKeys);
if ($key === "*") {
$arrayKeys = array_keys($params[$actualKeys[0]]);
$innerActualKeys = array_splice($actualKeys, 0, -1);
foreach ($arrayKeys as $arrayKey) {
$innerActualKeys[] = $arrayKey;
$this->validate($params, $validator, $innerActualKeys);
array_pop($innerActualKeys);
}
} else {
$this->validate($params, $validator, $actualKeys);
}
} else {
try {
$validator->assert($param);
Expand Down
28 changes: 28 additions & 0 deletions tests/ValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,34 @@ function ($message) {
),
),
),
//Multiple nested JSON validation with errors
array(
array(
'messages' => array(
'*' => array(
'title' => v::stringType()->length(6, null)->setName("messageTitle")
)
),
),
null,
true,
array(
'messages.0.title' => array(
'messageTitle must have a length greater than 6',
),
),
'JSON',
array(
'messages' => array(
array(
'title' => 'Title'
),
array(
'title' => 'Long title'
),
),
),
),

//XML validation without errors
array(
Expand Down