|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Tests\Fiv\Form\Validator; |
|
4
|
|
|
|
|
5
|
|
|
use Fiv\Form\Form; |
|
6
|
|
|
use Fiv\Form\FormData; |
|
7
|
|
|
use Fiv\Form\Validator\CallBackValidator; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* |
|
11
|
|
|
*/ |
|
12
|
|
|
class CallBackValidatorTest extends \PHPUnit_Framework_TestCase { |
|
13
|
|
|
|
|
14
|
|
|
public function testLen() { |
|
15
|
|
|
$lengthValidator = new CallBackValidator(function ($value) { |
|
16
|
|
|
return strlen($value) > 3 and strlen($value) < 10; |
|
17
|
|
|
}); |
|
18
|
|
|
|
|
19
|
|
|
$lengthValidator->setErrorMessage('Invalid value'); |
|
20
|
|
|
|
|
21
|
|
|
$form = new Form(); |
|
22
|
|
|
$form->input('login') |
|
23
|
|
|
->addValidator($lengthValidator); |
|
24
|
|
|
|
|
25
|
|
|
$form->handle(new FormData('post', [ |
|
26
|
|
|
$form->getUid() => 1, |
|
27
|
|
|
'login' => 'testLogin', |
|
28
|
|
|
])); |
|
29
|
|
|
|
|
30
|
|
|
$this->assertTrue($form->isValid()); |
|
31
|
|
|
$this->assertFalse($lengthValidator->hasErrors()); |
|
32
|
|
|
|
|
33
|
|
|
$form->handle(new FormData('post', [ |
|
34
|
|
|
$form->getUid() => 1, |
|
35
|
|
|
'login' => 'tes', |
|
36
|
|
|
])); |
|
37
|
|
|
|
|
38
|
|
|
$this->assertFalse($form->isValid()); |
|
39
|
|
|
$this->assertTrue($lengthValidator->hasErrors()); |
|
40
|
|
|
|
|
41
|
|
|
$form->handle(new FormData('post', [ |
|
42
|
|
|
$form->getUid() => 1, |
|
43
|
|
|
'login' => 'testtesttesttesttesttesttesttest', |
|
44
|
|
|
])); |
|
45
|
|
|
|
|
46
|
|
|
$this->assertFalse($form->isValid()); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
|
|
50
|
|
|
public function testEmailVirtualDbValidation() { |
|
51
|
|
|
$form = new Form(); |
|
52
|
|
|
|
|
53
|
|
|
$existEmailList = [ |
|
54
|
|
|
'[email protected]', |
|
55
|
|
|
'[email protected]', |
|
56
|
|
|
]; |
|
57
|
|
|
|
|
58
|
|
|
$callBackValidator = (new CallBackValidator(function ($value) use ($existEmailList) { |
|
59
|
|
|
if (empty($value)) { |
|
60
|
|
|
return true; |
|
61
|
|
|
} |
|
62
|
|
|
if (in_array($value, $existEmailList)) { |
|
63
|
|
|
return false; |
|
64
|
|
|
} |
|
65
|
|
|
return true; |
|
66
|
|
|
}))->setErrorMessage('Email already exist!'); |
|
67
|
|
|
|
|
68
|
|
|
$input = $form->input('email'); |
|
69
|
|
|
$input->addValidator($callBackValidator); |
|
70
|
|
|
|
|
71
|
|
|
$form->handle(new FormData('post', [ |
|
72
|
|
|
$form->getUid() => 1, |
|
73
|
|
|
'email' => '[email protected]', |
|
74
|
|
|
])); |
|
75
|
|
|
|
|
76
|
|
|
$this->assertFalse($form->isValid()); |
|
77
|
|
|
$this->assertEquals('Email already exist!', $callBackValidator->getFirstError()); |
|
78
|
|
|
|
|
79
|
|
|
$form->handle(new FormData('post', [ |
|
80
|
|
|
$form->getUid() => 1, |
|
81
|
|
|
'email' => '[email protected]', |
|
82
|
|
|
])); |
|
83
|
|
|
|
|
84
|
|
|
$this->assertTrue($form->isValid()); |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|