| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124 |
- <?php
- /**
- * 重庆赤晓店信息科技有限公司
- * https://www.chixiaodian.com
- * Copyright (c) 2023 赤店商城 All rights reserved.
- */
- namespace app\utils;
- use yii\validators\EmailValidator;
- use yii\validators\NumberValidator;
- use yii\validators\StringValidator;
- use yii2mod\validators\PhoneValidator;
- class Validator
- {
- public $error;
- public $success;
- /**
- * Validator constructor.
- * @param $attribute
- * [
- * ['string',$value|string or array,[],messge|string or array]
- * ]
- */
- public function __construct($attribute)
- {
- if (!is_array($attribute[0])) {
- $attribute = [ $attribute ];
- }
- foreach ($attribute as $v) {
- $rm = method_exists(self::class,$v[0]) ? new \ReflectionMethod(self::class,$v[0]) : false;
- if ($rm === false || !$rm->isStatic()) {
- $this->success = false;
- $this->error = json_encode($attribute).'方法不存在';
- return false;
- }
- if (is_array($v[1])) {
- foreach ($v[1] as $key => $val) {
- if (!call_user_func_array([self::class,$v[0]],[$val,$v[2]])) {
- $this->success = false;
- $this->error = isset($v[3]) && isset($v[3][$key]) ? $v[3][$key] : false;
- return false;
- }
- }
- } else {
- if (!call_user_func_array([self::class,$v[0]],[$v[1],$v[2]])) {
- $this->success = false;
- $this->error = isset($v[3]) ? $v[3] : false;
- return false;
- }
- }
- $this->success = true;
- $this->error = null;
- return true;
- }
- }
- /**
- * 验证字符串
- * @param $value
- * @param $attribute
- * @return bool
- */
- public static function string ($value, $attribute)
- {
- $valid = new StringValidator($attribute);
- return $valid->validate($value,$error);
- }
- /**
- * 验证数字
- * @param $value
- * @param $attribute
- * @return bool
- */
- public static function number ($value, $attribute)
- {
- $valid = new NumberValidator($attribute);
- return $valid->validate($value, $error);
- }
- /**
- * 验证邮箱
- * @param $value
- * @return bool
- */
- public static function email ($value, $attribute = [])
- {
- $valid = new EmailValidator();
- return $valid->validate($value, $error);
- }
- /**
- * 验证手机号
- * @param $value
- * @return bool
- */
- public static function phone ($value, $attribute = [])
- {
- $chars = "/^1[3-9]\d{9}$/";
- if (preg_match($chars, $value)){
- return true;
- }else{
- return false;
- }
- }
- /**
- * 验证单选
- * @param $value
- * @param $attribute
- * @return bool
- */
- public static function radio ($value, $attribute)
- {
- if (in_array($value,$attribute)) {
- return true;
- }else {
- return false;
- }
- }
- }
|