| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- <?php
- namespace common\components;
- use Yii;
- class validate
- {
-
- //简单检查,只查有没传参数,具体参数值不管
- public static function easyCheck($valid, $data)
- {
- $keyList = array_keys($data);
- foreach ($valid as $val) {
- if (in_array($val, $keyList) == false) {
- util::fail('缺少必要参数:' . $val);
- }
- }
- }
-
- // 示例 $valid = [['title', 'numeric|min:2|max:40', '请确认标题'],['targetId', 'required|int', '目标不存在'],['type', 'required|int|min:2', '类型无效']];
- public static function check($valid, $data)
- {
- $validPass = true;
- foreach ($valid as $val) {
- if (count($val) != 3) {
- util::fail('验证参数设置错误');
- }
- $field = isset($val[0]) ? $val[0] : '';
- $requireString = isset($val[1]) ? $val[1] : '';
- $message = isset($val[2]) ? $val[2] : '';
- if (empty($requireString)) {
- util::fail('验证参数设置错误!');
- }
- $requireArr = explode('|', $requireString);
- if (in_array('required', $requireArr)) {
- if (isset($data[$field]) == false || strlen($data[$field]) == 0) {
- util::fail($message);
- }
- } else {
- if (isset($data[$field]) == false) {
- continue;
- }
- }
- $currentValue = $data[$field];
- $hasError = false;
- foreach ($requireArr as $requireItem) {
- $min = strstr($requireItem, 'min:') ? (int)str_replace('min:', '', $requireItem) : 0;
- $max = strstr($requireItem, 'max:') ? (int)str_replace('max:', '', $requireItem) : 0;
- if ($min > 0) {
- if (strlen(trim($currentValue)) < $min) {
- $hasError = true;
- }
- }
- if ($max > 0) {
- if (strlen(trim($currentValue)) > $max) {
- $hasError = true;
- }
- }
- if ($min == 0 && $max == 0) {
- if (strlen(trim($currentValue)) == 0) {
- $hasError = true;
- }
- }
- if (strlen(trim($currentValue)) == 0) {
- $hasError = true;
- }
- if ($requireItem == 'int') {
- if (is_numeric($currentValue) == false) {
- $hasError = true;
- }
- }
- if ($requireItem == 'numeric') {
- if (is_numeric($currentValue) == false) {
- $hasError = true;
- }
- }
- if ($hasError) {
- util::fail($message);
- }
- }
- }
- return $validPass;
- }
- }
|