diff --git a/README.md b/README.md index 454cc76..1f3c4e8 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ composer require tinywan/validate ``` -## 用法 +## 基础用法 ~~~php check($data)) { } ~~~ +## 助手函数(推荐) + +验证器调用代码如下: +```php +$data = [ + 'name' => 'Tinywan', + 'age' => 24, + 'email' => 'Tinywan@163.com' +]; +validate($data, \app\index\validate\UserValidate::class . '.issue'); +``` +> 验证错误会自动抛出异常 + 更多用法可以参考6.0完全开发手册的[验证](https://www.kancloud.cn/manual/thinkphp6_0/1037623)章节 diff --git a/src/helper.php b/src/helper.php index 7e077d9..3004192 100644 --- a/src/helper.php +++ b/src/helper.php @@ -8,38 +8,38 @@ declare (strict_types = 1); namespace Tinywan\Validate; +use function is_array; +use function strpos; +use function explode; if (!function_exists('validate')) { /** * 生成验证对象 - * @param string|array $validate 验证器类名或者验证规则数组 - * @param array $message 错误提示信息 - * @param bool $batch 是否批量验证 - * @param bool $failException 是否抛出异常 + * @param array $data 数据 + * @param string|array $validate 验证器类名或者验证规则数组 + * @param array $message 错误提示信息 + * @param bool $batch 是否批量验证 + * @param bool $failException 是否抛出异常 * @return Validate */ - function validate($validate = '', array $message = [], bool $batch = false, bool $failException = true): Validate + function validate(array $data, $validate = '', array $message = [], bool $batch = false, bool $failException = true): Validate { - if (is_array($validate) || '' === $validate) { + if (is_array($validate)) { $v = new Validate(); - if (is_array($validate)) { - $v->rule($validate); - } + $v->rule($validate); } else { if (strpos($validate, '.')) { - // 支持场景 [$validate, $scene] = explode('.', $validate); } - $class = false !== strpos($validate, '\\') ? $validate : $validate; - $v = new $class(); - if (!empty($scene)) { $v->scene($scene); } } - return $v->message($message)->batch($batch)->failException($failException); + $v->message($message); + $v->batch($batch); + return $v->failException($failException)->check($data); } } \ No newline at end of file