validate.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. $validPass = true;
  11. foreach ($valid as $val) {
  12. if (in_array($val, $keyList) == false) {
  13. error::instance()->setError('缺少必要参数:' . $val);
  14. $validPass = false;
  15. break;
  16. }
  17. }
  18. return $validPass;
  19. }
  20. // 示例 $valid = [['title', 'numeric|min:2|max:40', '请确认标题'],['targetId', 'required|int', '目标不存在'],['type', 'required|int|min:2', '类型无效']];
  21. public static function check($valid, $data)
  22. {
  23. $validPass = true;
  24. foreach ($valid as $val) {
  25. if (count($val) != 3) {
  26. util::fail('验证参数设置错误');
  27. }
  28. $field = isset($val[0]) ? $val[0] : '';
  29. $requireString = isset($val[1]) ? $val[1] : '';
  30. $message = isset($val[2]) ? $val[2] : '';
  31. if (empty($requireString)) {
  32. util::fail('验证参数设置错误!');
  33. }
  34. $requireArr = explode('|', $requireString);
  35. if (in_array('required', $requireArr)) {
  36. if (isset($data[$field]) == false || strlen($data[$field]) == 0) {
  37. util::fail($message);
  38. }
  39. } else {
  40. if (isset($data[$field]) == false) {
  41. continue;
  42. }
  43. }
  44. $currentValue = $data[$field];
  45. $hasError = false;
  46. foreach ($requireArr as $requireItem) {
  47. $min = strstr($requireItem, 'min:') ? (int)str_replace('min:', '', $requireItem) : 0;
  48. $max = strstr($requireItem, 'max:') ? (int)str_replace('max:', '', $requireItem) : 0;
  49. if ($min > 0) {
  50. if (strlen(trim($currentValue)) < $min) {
  51. $hasError = true;
  52. }
  53. }
  54. if ($max > 0) {
  55. if (strlen(trim($currentValue)) > $max) {
  56. $hasError = true;
  57. }
  58. }
  59. if ($min == 0 && $max == 0) {
  60. if (strlen(trim($currentValue)) == 0) {
  61. $hasError = true;
  62. }
  63. }
  64. if (strlen(trim($currentValue)) == 0) {
  65. $hasError = true;
  66. }
  67. if ($requireItem == 'int') {
  68. if (is_numeric($currentValue) == false) {
  69. $hasError = true;
  70. }
  71. }
  72. if ($requireItem == 'numeric') {
  73. if (is_numeric($currentValue) == false) {
  74. $hasError = true;
  75. }
  76. }
  77. if ($hasError) {
  78. util::fail($message);
  79. }
  80. }
  81. }
  82. return $validPass;
  83. }
  84. }