thinkPHP5——验证类之把所有验证方法放到一个类中

主要文件:

1.VUser.php的主要代码:

namespace app\index\validate;
use think\Validate;
class VUser extends Validate{
    //验证用户信息修改
    public static function vupdate(){
        $rule = [
            'id'=>'require|IsInt',
            'password'=>'require|min:6',
        ];
        $message = [
            'id.require'=>'id不能为空',
            'password.require'=>'密码不能为空',
            'password.min'=>'密码不得少于6位',
        ];
        return ['rule' => $rule,'message' => $message];
    }
    protected function IsInt($value,$field){
        //参数依次为验证数据,验证规则,全部数据(数组),字段名
        //这里我们要判断的验证的数据要求必须为正整型
        if(is_numeric($value) && is_int($value+0) && ($value+0) > 0){
        //is_numeric() 函数用于检测变量是否为数字或数字字符串。
        //$value+0的意义,把数字字符串转为数字
            return true;
        }else{
            //如果不符合我们的条件,返回错误信息,在控制器中可以用getError()方法输出
            return $field.'id不是整型';
        }
    }
}

2.Validatefun.php的主要代码:(ValidateFun 类继承了tp5自带的验证方法,把自定义的验证加在ValidateFun这个类里)

namespace app\index\validate;
use think\Validate;
class Validatefun extends Validate{
    public function __construct(array $rules = [], $message = [], $field = [])
    {
        parent::__construct($rules, $message, $field);
    }
}

3.member.php的主要代码:

namespace app\index\controller;
use app\index\model\User;
use app\index\validate\Validatefun;
use app\index\validate\VUser;
use think\Db;
use think\Loader;

class Member{
    /**
     * 修改用户信息
     */
    public function edit_info($json){
        //接收参数
        $data = json_decode($json,true);
        //参数验证
        $Vupdate = VUser::vupdate();
        $result = new Validatefun($Vupdate['rule'],$Vupdate['message']);
        if(!$result->check($data)){
            return json(['code'=>400,'msg'=>$result->getError()]);
        }
        else{
            return json(['code'=>200,'msg'=>'验证成功']);
        }
   
    }
}

4.验证方法,在浏览器中输入地址:

http://angryshan.com/index.php/index/member/edit_info/json/{"username":1,"password":123}

json前面是使用控制器方法的地址

猜你喜欢

转载自blog.csdn.net/angryshan/article/details/81485512
今日推荐