Skip to content

Commit d24449c

Browse files
committed
Rules: added removeRule()
1 parent b839134 commit d24449c

File tree

2 files changed

+77
-0
lines changed

2 files changed

+77
-0
lines changed

src/Forms/Rules.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,26 @@ public function addRule($validator, $errorMessage = null, $arg = null)
9292
}
9393

9494

95+
/**
96+
* Removes a validation rule for the current control.
97+
* @param callable|string $validator
98+
* @return static
99+
*/
100+
public function removeRule($validator)
101+
{
102+
if ($validator === Form::REQUIRED) {
103+
$this->required = null;
104+
} else {
105+
foreach ($this->rules as $i => $rule) {
106+
if (!$rule->branch && $rule->validator === $validator) {
107+
unset($this->rules[$i]);
108+
}
109+
}
110+
}
111+
return $this;
112+
}
113+
114+
95115
/**
96116
* Adds a validation condition and returns new branch.
97117
* @return static new branch

tests/Forms/Rules.removeRule.phpt

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use Nette\Forms\Form;
6+
use Tester\Assert;
7+
8+
9+
require __DIR__ . '/../bootstrap.php';
10+
11+
12+
test(function () {
13+
$form = new Form;
14+
$input = $form->addText('text1');
15+
$input->setRequired();
16+
$input->addRule($form::EMAIL);
17+
18+
$rules = iterator_to_array($input->getRules());
19+
Assert::count(2, $rules);
20+
Assert::same($form::REQUIRED, $rules[0]->validator);
21+
Assert::same($form::EMAIL, $rules[1]->validator);
22+
23+
$input->getRules()->removeRule($form::EMAIL);
24+
25+
$rules = iterator_to_array($input->getRules());
26+
Assert::count(1, $rules);
27+
Assert::same($form::REQUIRED, $rules[0]->validator);
28+
29+
$input->getRules()->removeRule($form::REQUIRED);
30+
31+
$rules = iterator_to_array($input->getRules());
32+
Assert::count(0, $rules);
33+
});
34+
35+
36+
test(function () {
37+
$form = new Form;
38+
$input = $form->addText('text');
39+
$input->setRequired();
40+
41+
Assert::count(1, iterator_to_array($input->getRules()));
42+
$input->getRules()->removeRule($form::EMAIL);
43+
44+
Assert::count(1, iterator_to_array($input->getRules()));
45+
});
46+
47+
48+
test(function () {
49+
$form = new Form;
50+
$input = $form->addText('text');
51+
$input->addCondition($form::EMAIL);
52+
53+
Assert::count(1, iterator_to_array($input->getRules()));
54+
$input->getRules()->removeRule($form::EMAIL);
55+
56+
Assert::count(1, iterator_to_array($input->getRules()));
57+
});

0 commit comments

Comments
 (0)