Skip to content

Commit 1a068da

Browse files
author
xiajianjun
committed
update the document, change class name,update
1 parent ae314c1 commit 1a068da

File tree

5 files changed

+132
-53
lines changed

5 files changed

+132
-53
lines changed

document.md

Lines changed: 51 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,22 @@ _repositories_ add
2525

2626
run: `composer update`
2727

28+
<a name="how-to-use"></a>
2829
### how to use
2930

3031
- Method 1: create a new class
3132
e.g.
3233

33-
```
34-
<?php
34+
```php
3535

36-
use slimExtend\validate\Validator;
36+
use inhere\validate\Validation;
3737

38-
class PageRequest extends Validator
38+
class PageRequest extends Validation
3939
{
4040
public function rules()
4141
{
4242
return [
43-
['tagId,userId,freeTime', 'required', 'msg' => '{attr} is required!'],
43+
['tagId,title,userId,freeTime', 'required', 'msg' => '{attr} is required!'],
4444
['tagId', 'size', 'min'=>4, 'max'=>567], // 4<= tagId <=567
4545
['title', 'min', 'min' => 40],
4646
['freeTime', 'number'],
@@ -50,6 +50,7 @@ run: `composer update`
5050
}],
5151
['userId', 'number', 'scene' => 'scene1' ],
5252
['userId', 'int', 'scene' => 'scene2' ],
53+
['title', 'customValidator', 'msg' => '{attr} error msg!' ],
5354
['status', function($status)
5455
{
5556

@@ -61,6 +62,14 @@ run: `composer update`
6162
];
6263
}
6364

65+
// custom validator at the class. return a bool.
66+
protected function customValidator($title)
67+
{
68+
// some logic ...
69+
70+
return true; // Or false;
71+
}
72+
6473
// define field attribute's translate.
6574
public function attrTrans()
6675
{
@@ -77,9 +86,11 @@ run: `composer update`
7786
];
7887
}
7988
}
89+
```
90+
91+
use, at other class
8092

81-
//
82-
// use, at other class
93+
```php
8394

8495
$valid = PageRequest::make($_POST,)->validate();
8596
if ( $valid->fail() ) {
@@ -92,15 +103,15 @@ if ( $valid->fail() ) {
92103

93104
- Method 2: direct use
94105

95-
```
96-
<?php
97-
use slimExtend\validate\Validator;
106+
```php
107+
108+
use inhere\validate\Validation;
98109

99110
class SomeClass
100111
{
101112
public function demo()
102113
{
103-
$valid = Validator::make($_POST,[
114+
$valid = Validation::make($_POST,[
104115
// add rule
105116
['title', 'min', 'min' => 40],
106117
['freeTime', 'number'],
@@ -116,13 +127,36 @@ if ( $valid->fail() ) {
116127
}
117128
```
118129

130+
### how to add custom validator
131+
132+
- add in the subclass of the `inhere\validate\Validation`. see [how-to-use](#how-to-use) method 1.
133+
- add validator by method `addValidator`. e.g:
134+
135+
```php
136+
137+
$valid = Validation::make($_POST,[
138+
// add rule
139+
['title', 'min', 'min' => 40],
140+
['freeTime', 'number'],
141+
['title', 'checkTitle', 'msg' => 'Title didn't pass the validate!' ],
142+
])
143+
->addValidator('checkTitle',function($title){
144+
// some logic ...
145+
146+
return true; // if validate fail, return false.
147+
})
148+
->validate();
149+
150+
```
151+
119152
### keywords
120153

121154
- scene -- 设置验证场景
155+
122156
> 如果需要让一个验证器在多个类似情形下使用,在验证时也表明要验证的场景
123157
124158
```
125-
// at validator class
159+
// at a subclass of the Validation class
126160
<?php
127161
128162
'''
@@ -135,26 +169,28 @@ if ( $valid->fail() ) {
135169
];
136170
}
137171
```
138-
> 在下面设置了场景时,将只会使用上面的第 1 3 条规则. (第 1 条没有限制规则使用场景的,在所有场景都可用)
172+
173+
> 在下面设置了场景时,将只会使用上面的第 1,3 条规则. (第 1 条没有限制规则使用场景的,在所有场景都可用)
139174
140175
```
141176
// at logic
142177
<?php
143178
144179
...
145-
$valid = ValidatorClass::make($_POST)->setScene('scene2')->validate();
180+
$valid = ValidationClass::make($_POST)->setScene('scene2')->validate();
146181
...
147182
148183
```
149184

150185
- when -- 规则的前置条件
186+
151187
> 只有在先满足了(`when`)前置条件时才会验证这条规则
152188
如在下面的例子中,检查到第二条规则时,会先执行闭包(`when`),
153189
当其返回 `true` 验证此条规则,
154190
否则不会验证此条规则
155191

156192
```
157-
// at validator class
193+
// at a subclass of the Validation class
158194
<?php
159195
160196
'''

example/DataModel.php

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,14 @@
11
<?php
22

3-
class DataModel extends \slimExtend\validate\Validator
3+
/**
4+
* Class DataModel
5+
*
6+
* custom extend the trait 'ValidationTrait' like the class 'Validation'
7+
*/
8+
class DataModel
49
{
510

11+
use \inhere\validate\ValidationTrait;
12+
613

714
}

example/PageRequest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
/**
1010
* Class PageRequest
1111
*/
12-
class PageRequest extends \slimExtend\validate\Validator
12+
class PageRequest extends \inhere\validate\Validation
1313
{
1414
public function rules()
1515
{

src/Validator.php renamed to src/Validation.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@
99
namespace inhere\validate;
1010

1111
/**
12-
* Class Validator
12+
* Class Validation
1313
* @package inhere\validate
1414
*/
15-
class Validator
15+
class Validation
1616
{
17-
use ValidatorTrait {
17+
use ValidationTrait {
1818
set as traitSet;
1919
get as traitGet;// Methods to define an alias, can be used in the current class.
2020
}

src/ValidatorTrait.php renamed to src/ValidationTrait.php

Lines changed: 69 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,12 @@
1010
namespace inhere\validate;
1111

1212
/**
13-
* Trait ValidatorTrait
13+
* Trait ValidationTrait
1414
* @package inhere\validate
1515
*
1616
* @property array $data
1717
*/
18-
trait ValidatorTrait
18+
trait ValidationTrait
1919
{
2020
/**
2121
* 当前验证的场景 -- 如果需要让一个验证器在多个类似情形下使用
@@ -49,6 +49,11 @@ trait ValidatorTrait
4949
*/
5050
private $_rules = [];
5151

52+
/**
53+
* @var array
54+
*/
55+
private $_validators = [];
56+
5257
/**
5358
* attribute field translate list
5459
* @var array
@@ -99,7 +104,7 @@ public function attrTrans()
99104
}
100105

101106
/**
102-
* custom validator's message
107+
* custom validator's message, to override default message.
103108
* @return array
104109
*/
105110
public function messages()
@@ -115,7 +120,7 @@ public function messages()
115120
public function beforeValidate(){}
116121

117122
/**
118-
* [Validator::required] 验证是必定被调用的
123+
* [ValidatorList::required] 验证是必定被调用的
119124
* @author inhere
120125
* @date 2015-08-11
121126
* @param array $onlyChecked 只检查一部分属性
@@ -217,28 +222,62 @@ protected function doValidate($data, $name, $validator, $copy)
217222

218223
// if it's a closure
219224
if ( is_callable($validator) && $validator instanceof \Closure) {
220-
$result = call_user_func_array($validator, $copy);
225+
$callback = $validator;
221226
$validator = 'callback';
222227

223-
// if it is a method of the subclass.
228+
// if it is a custom add callback in the property {@see $_validators}.
229+
} elseif ( is_string($validator) && isset($this->_validators['validator']) ) {
230+
231+
$callback = $this->_validators['validator'];
232+
233+
// if it is a custom method of the subclass.
224234
} elseif ( is_string($validator) && method_exists($this, $validator) ) {
225235

226-
$result = call_user_func_array( [ $this, $validator ] , $copy);
236+
$callback = [ $this, $validator ];
227237

228238
// it's a method of the class 'ValidatorList'
229-
} elseif ( is_callable([ValidatorList::class, $validator]) ) {
239+
} elseif ( is_string($validator) && is_callable([ValidatorList::class, $validator]) ) {
230240

231-
$result = call_user_func_array( [ ValidatorList::class, $validator ] , $copy);
241+
$callback = [ ValidatorList::class, $validator];
232242
} else {
233243
throw new \InvalidArgumentException("validator [$validator] don't exists!");
234244
}
245+
246+
$result = call_user_func_array($callback, $copy);
235247
}
236248

237249
return [$result,$validator];
238250
}
239251

240252
public function afterValidate(){}
241253

254+
/**
255+
* add a custom validator
256+
*
257+
* ```
258+
* $valid = ValidatorClass::make($_POST)
259+
* ->addValidator('name',function($var [, $arg1, $arg2 ... ]){
260+
* return $var === 23;
261+
* });
262+
* $valid->validate();
263+
* ```
264+
*
265+
* @param string $name
266+
* @param \Closure $callback
267+
* @param string $msg
268+
* @return $this
269+
*/
270+
public function addValidator($name, \Closure $callback, $msg = '')
271+
{
272+
$this->_validators[$name] = $callback;
273+
274+
if ($msg) {
275+
$this->defaultMessages[$name] = $msg;
276+
}
277+
278+
return $this;
279+
}
280+
242281
/**
243282
* @return array
244283
*/
@@ -345,33 +384,30 @@ public function lastError($onlyMsg=true)
345384
* (过滤器)默认的错误提示信息
346385
* @return array
347386
*/
348-
public function defaultMessages()
349-
{
350-
return [
351-
'int' => '{attr} must be an integer!',
352-
'number' => '{attr} must be an integer greater than 0!',
353-
'bool' => '{attr} must be is boolean!',
354-
'float' => '{attr} must be is float!',
355-
'regexp' => '{attr} does not meet the conditions',
356-
'url' => '{attr} not is url address!',
357-
'email' => '{attr} not is email address!',
358-
'ip' => '{attr} not is ip address!',
359-
'required' => '{attr} is not block!',
360-
'length' => '{attr} length must at rang {min} ~ {max}',
361-
'size' => '{attr} must be an integer and at rang {min} ~ {max}',
362-
'min' => '{attr} minimum boundary is {value}',
363-
'max' => '{attr} maximum boundary is {value}',
364-
'in' => '{attr} must in ({value})',
365-
'string' => '{attr} must be a string',
366-
'isArray' => '{attr} must be an array',
367-
'callback' => 'The custom callback validation fails of the [{attr}]!',
368-
'_' => '{attr} validation is not through!',
369-
];
370-
}
387+
public $defaultMessages = [
388+
'int' => '{attr} must be an integer!',
389+
'number' => '{attr} must be an integer greater than 0!',
390+
'bool' => '{attr} must be is boolean!',
391+
'float' => '{attr} must be is float!',
392+
'regexp' => '{attr} does not meet the conditions',
393+
'url' => '{attr} not is url address!',
394+
'email' => '{attr} not is email address!',
395+
'ip' => '{attr} not is ip address!',
396+
'required' => '{attr} is not block!',
397+
'length' => '{attr} length must at rang {min} ~ {max}',
398+
'size' => '{attr} must be an integer and at rang {min} ~ {max}',
399+
'min' => '{attr} minimum boundary is {value}',
400+
'max' => '{attr} maximum boundary is {value}',
401+
'in' => '{attr} must in ({value})',
402+
'string' => '{attr} must be a string',
403+
'isArray' => '{attr} must be an array',
404+
'callback' => 'The custom callback validation fails of the [{attr}]!',
405+
'_' => '{attr} validation is not through!',
406+
];
371407

372408
public function getMessages()
373409
{
374-
return array_merge($this->defaultMessages(), $this->messages());
410+
return array_merge($this->defaultMessages, $this->messages());
375411
}
376412

377413
/**

0 commit comments

Comments
 (0)