validate.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace common\components;
  3. use Yii;
  4. class validate
  5. {
  6. //简单检查,只查有没传参数,具体参数值不管
  7. public static function easyCheck($valid, $data)
  8. {
  9. $keyList = array_keys($data);
  10. foreach ($valid as $val) {
  11. if (in_array($val, $keyList) == false) {
  12. util::fail('缺少必要参数:' . $val);
  13. }
  14. }
  15. }
  16. // 示例 $valid = [['title', 'numeric|min:2|max:40', '请确认标题'],['targetId', 'required|int', '目标不存在'],['type', 'required|int|min:2', '类型无效']];
  17. public static function check($valid, $data)
  18. {
  19. $validPass = true;
  20. foreach ($valid as $val) {
  21. if (count($val) != 3) {
  22. util::fail('验证参数设置错误');
  23. }
  24. $field = isset($val[0]) ? $val[0] : '';
  25. $requireString = isset($val[1]) ? $val[1] : '';
  26. $message = isset($val[2]) ? $val[2] : '';
  27. if (empty($requireString)) {
  28. util::fail('验证参数设置错误!');
  29. }
  30. $requireArr = explode('|', $requireString);
  31. if (in_array('required', $requireArr)) {
  32. if (isset($data[$field]) == false || strlen($data[$field]) == 0) {
  33. util::fail($message);
  34. }
  35. } else {
  36. if (isset($data[$field]) == false) {
  37. continue;
  38. }
  39. }
  40. $currentValue = $data[$field];
  41. $hasError = false;
  42. foreach ($requireArr as $requireItem) {
  43. $min = strstr($requireItem, 'min:') ? (int)str_replace('min:', '', $requireItem) : 0;
  44. $max = strstr($requireItem, 'max:') ? (int)str_replace('max:', '', $requireItem) : 0;
  45. if ($min > 0) {
  46. if (strlen(trim($currentValue)) < $min) {
  47. $hasError = true;
  48. }
  49. }
  50. if ($max > 0) {
  51. if (strlen(trim($currentValue)) > $max) {
  52. $hasError = true;
  53. }
  54. }
  55. if ($min == 0 && $max == 0) {
  56. if (strlen(trim($currentValue)) == 0) {
  57. $hasError = true;
  58. }
  59. }
  60. if (strlen(trim($currentValue)) == 0) {
  61. $hasError = true;
  62. }
  63. if ($requireItem == 'int') {
  64. if (is_numeric($currentValue) == false) {
  65. $hasError = true;
  66. }
  67. }
  68. if ($requireItem == 'numeric') {
  69. if (is_numeric($currentValue) == false) {
  70. $hasError = true;
  71. }
  72. }
  73. if ($hasError) {
  74. util::fail($message);
  75. }
  76. }
  77. }
  78. return $validPass;
  79. }
  80. }