Skip to content
Open
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
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

## 2.6.3 under development

- no changes in this release.
- Bug #752: Allow access to sibling properties in nested validation context, e.g. in `when` callbacks and
`targetProperty` of compare rules (@WarLikeLaux, @vjik)

## 2.6.2 November 23, 2026

Expand Down
60 changes: 57 additions & 3 deletions docs/guide/en/built-in-rules-nested.md
Original file line number Diff line number Diff line change
Expand Up @@ -388,10 +388,15 @@ attributes] section.
- For more information about possible data / rules combinations passed for validation, refer to the [Using validator]
section.

### Conditional validation within nested structures
### Accessing sibling properties

When using `when` callbacks inside `Nested`, the validation context provides access to sibling properties — other
properties at the same nesting level. Use `$context->getDataSet()->getPropertyValue()` to read them.
For rules attached to named properties, `Nested` validates a property together with its whole scope. Because of
this, the validation context provides access to sibling properties — other properties at the same nesting level:

- in `when` callbacks and custom rules, via `$context->getDataSet()->getPropertyValue()`;
- in comparison rules, via the `targetProperty` option.

#### `when` callbacks

For example, to require `content` only when `isEnabled` is `true`:

Expand Down Expand Up @@ -426,6 +431,53 @@ $result = (new Validator())->validate($data, $rules);
This works at any depth, including when combined with `Each`. For more details and examples, see the
[Conditional validation] guide.

#### Comparison rules

Comparison rules can compare the validated property with a sibling one. Use the `targetProperty` option for this:

```php
use Yiisoft\Validator\Rule\Equal;
use Yiisoft\Validator\Rule\Nested;
use Yiisoft\Validator\Rule\Number;
use Yiisoft\Validator\Validator;

$data = [
'discountPercent' => 10,
'confirmedDiscountPercent' => 10,
];
$rules = new Nested([
'discountPercent' => new Number(min: 0),
'confirmedDiscountPercent' => new Equal(targetProperty: 'discountPercent'),
]);
$result = (new Validator())->validate($data, $rules);
```

Here `confirmedDiscountPercent` must be equal to the sibling `discountPercent` property. For more comparison options,
see the [`Compare` rule] guide.

#### Custom rules

A custom rule handler receives a `ValidationContext` as the third argument of its `validate()` method. Sibling
properties are resolved there the same way:

```php
public function validate(mixed $value, RuleInterface $rule, ValidationContext $context): Result
{
$isEnabled = (bool) $context->getDataSet()->getPropertyValue('isEnabled');
// ...
}
```

For more information about creating custom rules, see the [Creating custom rules] guide.

#### Numeric keys

A rule attached to a numeric key — an integer key like `0` or a path whose last segment is numeric, like
`'items.1'` — behaves differently: the selected value is validated as is, without the containing list. Sibling items
are not available in this case — `$context->getDataSet()->getPropertyValue()` returns `null` for them, and the
`targetProperty` option cannot reference them. To access properties of the same item in a list, combine `Each` with
`Nested` as shown above.

### Using keys containing separator / shortcut

If a key contains the separator (`.`), or `Each` shortcut (`*`), it must be escaped with backslash (`\`) in
Expand Down Expand Up @@ -501,5 +553,7 @@ $data = [
[Basic usage]: #basic-usage-one-to-one-relation
[JSFiddle]: https://jsfiddle.net/fys8uadr/
[Conditional validation]: conditional-validation.md
[`Compare` rule]: built-in-rules-compare.md
[Creating custom rules]: creating-custom-rules.md
[Configuring rules via PHP attributes]: configuring-rules-via-php-attributes.md
[Using validator]: using-validator.md
10 changes: 10 additions & 0 deletions docs/guide/en/conditional-validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,8 +343,18 @@ $rules = new Nested([
$result = (new Validator())->validate($data, $rules);
```

Sibling access works because, for named properties, `Nested` uses the whole scope the property belongs to as the
validation data. The same data set is available in custom rules and in comparison rules with `targetProperty`, see
the [`Nested` rule] guide for details.

Note that only named properties provide such access. When a rule is attached to a numeric leaf — an integer key or a
path ending with a numeric segment, like `'items.1'` — the selected value is validated as is, without the containing
list. In this case `$context->getDataSet()->getPropertyValue()` returns `null` for any sibling property, and the
`targetProperty` option of comparison rules cannot reference them.

As an alternative to functions, callable classes can be used instead. This approach has the advantage of code reusability.
See the [Skip on empty] section for an example.

[Configuring empty condition in other rules]: #configuring-empty-condition-in-other-rules
[Skip on empty]: #skiponempty---skipping-a-rule-if-the-validated-value-is-empty
[`Nested` rule]: built-in-rules-nested.md
57 changes: 40 additions & 17 deletions src/Rule/NestedHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Yiisoft\Validator\RuleInterface;
use Yiisoft\Validator\ValidationContext;

use function array_key_exists;
use function array_slice;
use function is_array;
use function is_int;
Expand Down Expand Up @@ -68,11 +69,11 @@ public function validate(mixed $value, RuleInterface $rule, ValidationContext $c
$compoundResult = new Result();

foreach ($rule->getRules() as $valuePath => $rules) {
if ($rule->isPropertyPathRequired() && !ArrayHelper::pathExists($data, $valuePath)) {
$valuePathList = is_int($valuePath)
? [$valuePath]
: StringHelper::parsePath($valuePath);
$valuePathList = is_int($valuePath)
? [$valuePath]
: StringHelper::parsePath($valuePath);

if ($rule->isPropertyPathRequired() && !ArrayHelper::pathExists($data, $valuePath)) {
$compoundResult->addError(
$rule->getNoPropertyPathMessage(),
[
Expand All @@ -86,32 +87,32 @@ public function validate(mixed $value, RuleInterface $rule, ValidationContext $c
continue;
}

$validatedValue = ArrayHelper::getValueByPath($data, $valuePath);
$property = end($valuePathList);
$validateValueItself = is_int($valuePath) || (string) (int) $property === $property;

if (is_int($valuePath)) {
$itemResult = $context->validate($validatedValue, $rules);
} else {
$valuePathList = StringHelper::parsePath($valuePath);
$property = end($valuePathList);
$itemResult = $context->validate(
ArrayHelper::keyExists($data, $valuePathList) ? [$property => $validatedValue] : [],
$itemResult = $validateValueItself
? $context->validate(
ArrayHelper::getValueByPath($data, $valuePath),
$rules,
)
: $context->validate(
$this->getPropertyScopeData($data, $valuePathList),
[$property => $rules],
Comment thread
samdark marked this conversation as resolved.
Resolved
);
}

if ($itemResult->isValid()) {
continue;
}

foreach ($itemResult->getErrors() as $error) {
$valuePathList = is_int($valuePath)
? [$valuePath, ...$error->getValuePath()]
: [...StringHelper::parsePath($valuePath), ...array_slice($error->getValuePath(), 1)];
$errorValuePath = $validateValueItself
? [...$valuePathList, ...$error->getValuePath()]
: [...$valuePathList, ...array_slice($error->getValuePath(), 1)];

$compoundResult->addErrorWithoutPostProcessing(
$error->getMessage(),
$error->getParameters(),
$valuePathList,
$errorValuePath,
);
}
}
Expand All @@ -122,4 +123,26 @@ public function validate(mixed $value, RuleInterface $rule, ValidationContext $c

return $compoundResult;
}

/**
* Get the data of the scope a property with a given value path belongs to, so it also contains sibling
* properties. Only arrays are traversed, any other intermediate value is treated as a missing path.
*
* @param array $data The data to get the scope from.
* @param array<array-key, int|string> $valuePathList A parsed value path of the validated property.
*
* @return array The scope data. An empty array when the scope cannot be resolved.
*/
private function getPropertyScopeData(array $data, array $valuePathList): array
{
$scopeData = $data;
foreach (array_slice($valuePathList, 0, -1) as $key) {
if (!is_array($scopeData) || !array_key_exists($key, $scopeData)) {
return [];
}
$scopeData = $scopeData[$key];
}

return is_array($scopeData) ? $scopeData : [];
}
}
Loading
Loading