Skip to content

Commit e4a1bb5

Browse files
committed
allow to delegate rule validation on (Validated)Control
1 parent 0e1918f commit e4a1bb5

File tree

3 files changed

+33
-1
lines changed

3 files changed

+33
-1
lines changed

src/Forms/Controls/BaseControl.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@
1212
use Nette;
1313
use Nette\Forms\Control;
1414
use Nette\Forms\Form;
15+
use Nette\Forms\Rule;
1516
use Nette\Forms\Rules;
17+
use Nette\Forms\ValidatedControl;
18+
use Nette\Forms\Validator;
1619
use Nette\Utils\Html;
1720
use Stringable;
1821
use function array_unique, explode, func_get_arg, func_num_args, get_parent_class, implode, is_array, sprintf, str_contains;
@@ -38,7 +41,7 @@
3841
* @property-deprecated array $options
3942
* @property-read string $error
4043
*/
41-
abstract class BaseControl extends Nette\ComponentModel\Component implements Control
44+
abstract class BaseControl extends Nette\ComponentModel\Component implements Control, ValidatedControl
4245
{
4346
public static string $idMask = 'frm-%s';
4447

@@ -469,6 +472,16 @@ public function validate(): void
469472
}
470473

471474

475+
public function validateRule(Rule $rule, $args): bool
476+
{
477+
$op = $rule->validator;
478+
$cb = is_string($op) && strncmp($op, ':', 1) === 0
479+
? [Validator::class, 'validate' . ltrim($op, ':')]
480+
: $op;
481+
return $cb($rule, $args);
482+
}
483+
484+
472485
/**
473486
* Adds error message to the list.
474487
*/

src/Forms/Rules.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,10 @@ private function adjustOperation(Rule $rule): void
338338

339339
private static function getCallback(Rule $rule)
340340
{
341+
if ($rule->control instanceof ValidatedControl) {
342+
return $rule->control->validateRule(...);
343+
}
344+
341345
$op = $rule->validator;
342346
return is_string($op) && strncmp($op, ':', 1) === 0
343347
? [Validator::class, 'validate' . ltrim($op, ':')]

src/Forms/ValidatedControl.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
/**
4+
* This file is part of the Nette Framework (https://nette.org)
5+
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6+
*/
7+
8+
declare(strict_types=1);
9+
10+
namespace Nette\Forms;
11+
12+
interface ValidatedControl extends Control
13+
{
14+
function validateRule(Rule $rule, mixed $args): bool;
15+
}

0 commit comments

Comments
 (0)