Skip to content

Commit 23736c2

Browse files
committed
update logic. bug fixed
1 parent c45e40a commit 23736c2

File tree

7 files changed

+229
-129
lines changed

7 files changed

+229
-129
lines changed

.gitignore

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# Created by .ignore support plugin (hsz.mobi)
2+
### Example user template template
3+
### Example user template
4+
5+
# IntelliJ project files
6+
.idea/
7+
8+
### OSX template
9+
*.DS_Store
10+
11+
# Icon must end with two \r
12+
Icon
13+
14+
# Thumbnails
15+
._*
16+
17+

document.md

Lines changed: 39 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
## simple validator
1+
## a simple php data validator
22

33
### Install
44

@@ -156,11 +156,12 @@ $valid = Validation::make($_POST,[
156156
['title', 'required' ],
157157
['userId', 'number', 'scene' => 'scene1' ],
158158
['userId', 'int', 'scene' => 'scene2' ],
159+
['name', 'string', 'scene' => 'scene1,scene2' ],
159160
];
160161
}
161162
```
162163

163-
> 在下面设置了场景时,将只会使用上面的第 1,3 条规则. (第 1 条没有限制规则使用场景的,在所有场景都可用)
164+
> 在下面设置了场景时,将会使用上面的第 1,3,4 条规则. (第 1 条没有限制规则使用场景的,在所有场景都可用)
164165
165166
```php
166167

@@ -196,6 +197,40 @@ $valid = Validation::make($_POST,[
196197
}
197198
```
198199

200+
- skipOnEmpty -- 为空是否跳过验证
201+
202+
为空是否跳过验证,默认值是 `true`. (reference yii2)
203+
204+
> 'required' 规则不在此限制内.
205+
206+
如,有一条规则:
207+
208+
```
209+
['name', 'string'],
210+
```
211+
212+
提交的数据中 没有'name'字段或者 `$data['name']` 等于空都不会进行 `string` 验证;只有当`$data['name']`有值时才会验证是否是string
213+
214+
215+
如果要想为空时也检查, 请将此字段同时加入 'required' 规则中.
216+
也可以设置 `'skipOnEmpty' => false`:
217+
218+
```
219+
['name', 'string', 'skipOnEmpty' => false ]
220+
```
221+
222+
- isEmpty -- 是否为空判断
223+
224+
是否为空判断, 这个判断作为 `skipOnEmpty` 的依据.
225+
默认使用 `empty($data['attr'])` 来判断.
226+
227+
你也可以自定义判断规则
228+
229+
```
230+
['name', 'string', 'isEmpty' => function($data, $attr) {
231+
return true or false;
232+
}]
233+
```
199234

200235
### Existing validators
201236

@@ -212,9 +247,9 @@ validator | description | rule example
212247
`required` | validate required | `['tagId,userId', 'required' ]`
213248
`length` | validate length | ....
214249
`size` | validate size | `['tagId', 'size', 'min'=>4, 'max'=>567]`
215-
`min` | validate min | `['title', 'min', 'value' => 40],`
250+
`min` | validate min | `['title', 'min', 'value' => 40],]`
216251
`max` | validate max | ....
217-
`in` | validate in | ....
252+
`in` | validate in | `['id', 'in', 'value' => [1,2,3],]`
218253
`string` | validate string | ....
219254
`isArray` | validate is Array | ....
220255
`callback` | validate by custom callback | ....

example/DataModel.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,5 +10,19 @@ class DataModel
1010

1111
use \inhere\validate\ValidationTrait;
1212

13+
protected $data = [];
14+
15+
16+
/**
17+
* @param array $data
18+
* @return $this
19+
*/
20+
public function setData($data)
21+
{
22+
$this->data = $data;
23+
24+
return $this;
25+
}
26+
1327

1428
}

example/index.php

Lines changed: 50 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,12 @@
22

33
spl_autoload_register(function($class)
44
{
5-
$file = __DIR__ . '/' . $class. '.php';
5+
// e.g. "inhere\validate\ValidationTrait"
6+
if (strpos($class,'\\')) {
7+
$file = dirname(__DIR__) . '/src/' . trim(strrchr($class,'\\'),'\\'). '.php';
8+
} else {
9+
$file = __DIR__ . '/' . $class. '.php';
10+
}
611

712
if (is_file($file)) {
813
include $file;
@@ -14,30 +19,55 @@
1419
'tagId' => '234535',
1520
// 'freeTime' => 'sdfdffffffffff',
1621
'distanceRequire' => 'sdfdffffffffff',
17-
'note' => 'sdfdffffffffff',
18-
'insertTime' => '',
19-
'lastReadTime' => 'sdfdffffffffff',
22+
'note' => '',
23+
'insertTime' => '1456767657',
24+
'lastReadTime' => '1456767657',
2025
];
2126

2227
$rules = [
23-
['tagId,userId,freeTime', 'required', 'msg' => '{field} is required!'],
24-
['note', 'email'],
25-
['tagId', 'size', 'min'=>4, 'max'=>567, 'msg' => '{field} must is big!'], // 4<= tagId <=567
26-
['freeTime', 'size', 'min'=>4, 'max'=>567, 'msg' => '{field} must is big!'], // 4<= tagId <=567
27-
['userId', function($value){ echo $value."\n"; return false;}, 'msg' => '{field} check filare!'],
28+
['tagId,userId,freeTime', 'required', 'msg' => '{attr} is required!'],// set message
29+
['note', 'email', 'skipOnEmpty' => false], // set skipOnEmpty is false.
30+
['insertTime', 'email', 'scene' => 'otherScene' ],// set scene. will is not validate it on default.
31+
['tagId', 'size', 'min'=>4, 'max'=>567], // 4<= tagId <=567
32+
['freeTime', 'size', 'min'=>4, 'max'=>567, 'when' => function($data, $valid) {
33+
echo " use when pre-check\n";
34+
35+
// $valid is current validation instance.
36+
37+
return true;
38+
}], // 4<= tagId <=567
39+
40+
['userId', function($value, $data){
41+
echo " use custom validate\n";
42+
43+
var_dump($value, $data);
44+
45+
echo __LINE__ . "\n";
46+
47+
return false;
48+
}, 'msg' => 'userId check failure!'],
2849
];
2950

30-
/*
31-
$model = new TestModel();
32-
$ret = $model->load($_POST)->validate();
33-
*/
34-
$model = new DataModel($_POST,$rules);
35-
$ret = $model->validate([], true);
36-
37-
// echo "<pre>";
38-
var_dump($ret,
39-
$model->firstError()
51+
echo "use ValidationTrait\n";
52+
53+
//$model = new DataModel($_POST,$rules);
54+
$model = new DataModel;
55+
$model->setData($data)->setRules($rules);
56+
$model->validate();
57+
58+
var_dump(
59+
$model->all(),
60+
$model->getErrors()
4061
);
4162

63+
/*
64+
echo "--------------\n";
65+
echo "use Validation\n";
66+
67+
$valid = \inhere\validate\Validation::make($data, $rules)->validate();
4268
43-
// echo "</pre>";
69+
var_dump(
70+
$valid->all(),
71+
$valid->getErrors()
72+
);
73+
*/

src/StrHelper.php

Lines changed: 3 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -326,61 +326,14 @@ static public function toCamelCase($str, $upper_case_first_char = false)
326326
* Transform a CamelCase string to underscore_case string
327327
*
328328
* @param string $string
329+
* @param string $sep
329330
* @return string
330331
*/
331-
static public function toUnderscoreCase($string)
332+
static public function toUnderscoreCase($string, $sep='_')
332333
{
333334
// 'CMSCategories' => 'cms_categories'
334335
// 'RangePrice' => 'range_price'
335-
return self::strtolower(trim(preg_replace('/([A-Z][a-z])/', '_$1', $string), '_'));
336+
return self::strtolower(trim(preg_replace('/([A-Z][a-z])/', $sep . '$1', $string), $sep));
336337
}
337338

338-
/**
339-
* Convert a shorthand byte value from a PHP configuration directive to an integer value
340-
* @param string $value value to convert
341-
* @return int
342-
*/
343-
static public function convertBytes($value)
344-
{
345-
if (is_numeric($value))
346-
return $value;
347-
else {
348-
$value_length = strlen($value);
349-
$qty = (int)substr($value, 0, $value_length - 1 );
350-
$unit = self::strtolower(substr($value, $value_length - 1));
351-
switch ($unit)
352-
{
353-
case 'k':
354-
$qty *= 1024;
355-
break;
356-
case 'm':
357-
$qty *= 1048576;
358-
break;
359-
case 'g':
360-
$qty *= 1073741824;
361-
break;
362-
}
363-
return $qty;
364-
}
365-
}
366-
367-
/**
368-
* Format a number into a human readable format
369-
* e.g. 24962496 => 23.81M
370-
* @param $size
371-
* @param int $precision
372-
* @return string
373-
*/
374-
static public function formatBytes($size, $precision = 2)
375-
{
376-
if (!$size) {
377-
return '0';
378-
}
379-
380-
$base = log($size) / log(1024);
381-
$suffixes = array('', 'k', 'M', 'G', 'T');
382-
$floorBase = floor($base);
383-
384-
return round(pow(1024, $base - $floorBase), $precision).$suffixes[(int)$floorBase];
385-
}
386339
}

0 commit comments

Comments
 (0)