Skip to content

Commit 0a10145

Browse files
xificurkdg
authored andcommitted
Validator: add support for value objects (#202)
1 parent 7d2226b commit 0a10145

File tree

2 files changed

+66
-4
lines changed

2 files changed

+66
-4
lines changed

src/Forms/Validator.php

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,7 @@ public static function validateSubmitted(Controls\SubmitButton $control): bool
225225
*/
226226
public static function validateEmail(IControl $control): bool
227227
{
228-
return Validators::isEmail($control->getValue());
228+
return Validators::isEmail((string) $control->getValue());
229229
}
230230

231231

@@ -234,10 +234,12 @@ public static function validateEmail(IControl $control): bool
234234
*/
235235
public static function validateUrl(IControl $control): bool
236236
{
237-
if (Validators::isUrl($value = $control->getValue())) {
237+
$value = (string) $control->getValue();
238+
if (Validators::isUrl($value)) {
238239
return true;
239-
240-
} elseif (Validators::isUrl($value = "http://$value")) {
240+
}
241+
$value = "http://$value";
242+
if (Validators::isUrl($value)) {
241243
$control->setValue($value);
242244
return true;
243245
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
<?php
2+
3+
/**
4+
* Test: Nette\Forms\Controls\TextInput.
5+
*/
6+
7+
declare(strict_types=1);
8+
9+
use Nette\Forms\Form;
10+
use Tester\Assert;
11+
12+
13+
require __DIR__ . '/../bootstrap.php';
14+
15+
16+
class ValueObject
17+
{
18+
/** @var string */
19+
private $value;
20+
21+
22+
public function __construct(string $value)
23+
{
24+
$this->value = $value;
25+
}
26+
27+
28+
public function __toString(): string
29+
{
30+
return $this->value;
31+
}
32+
}
33+
34+
35+
test(function (): void { // e-mail
36+
$form = new Form;
37+
$input = $form->addEmail('email');
38+
39+
$input->setValue(new ValueObject('[email protected]'));
40+
Assert::type(ValueObject::class, $input->getValue());
41+
$form->validate();
42+
Assert::same([], $form->getErrors());
43+
});
44+
45+
46+
test(function (): void { // URL
47+
$form = new Form;
48+
$input = $form->addText('url')
49+
->addRule(Form::URL);
50+
51+
$input->setValue(new ValueObject('https://example.com'));
52+
Assert::type(ValueObject::class, $input->getValue());
53+
$form->validate();
54+
Assert::same([], $form->getErrors());
55+
56+
$input->setValue(new ValueObject('example.com'));
57+
Assert::type(ValueObject::class, $input->getValue());
58+
$form->validate();
59+
Assert::same([], $form->getErrors());
60+
});

0 commit comments

Comments
 (0)