首页> 实战笔录 >PHP开发笔记 >ThinkPHP ThinkPHP

TP5 自定义验证器

作者:小萝卜 2019-11-21 浏览 1242

简介TP内置验证功能提供两种验证方法,验证器、独立验证,以及自定义验证的代码分享

TP内置验证功能提供两种验证方法

  • 验证器(推荐)
$validate = Validate::make([
    'id' => 'require|integer',
]);
if ($validate->check(['id' => $id])) {
    
}

优点: 方便、快捷

缺点: 可读性和扩展性差

  • 独立验证
namespace appadminvalidate;
class Banner extends BaseValidate {
    protected $rule = [
        'name' => 'require|max:25',
        'age' => 'number|between:1,120',
        'email' => 'email',
    ];
    protected $message = [
        'name.require' => '名称必须',
        'name.max' => '名称最多不能超过25个字符',
        'age.number' => '年龄必须是数字',
        'age.between' => '年龄只能在1-120之间',
        'email' => '邮箱格式错误',
    ];
    protected $scene = [
        'edit' => ['name','age'],
    ];
}

 

官方提供了一些验证规则,如果不能满足需求可以自定义

建议自定义在验证器基类中,这样所有继承这个类的子验证器都可以使用这些验证方法

定义规则

    protected function isMobile($value) {
        $rule = '^1(3|4|5|7|8)[0-9]d{8}$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

 自定义验证器有以下几个参数

value:待验证的值

field:验证字段名

 

验证器推荐使用方法

定义验证器基类,继承 Validate类 ,在基类中定义一些公共验证规则和方法

<?php
namespace appadminvalidate;
use thinkValidate;

/**
 * Class BaseValidate
 * 验证类的基类
 */
class BaseValidate extends Validate {
    /**
     * 检测所有客户端发来的参数是否符合验证类规则
     * 基类定义了很多自定义验证方法
     * 这些自定义验证方法其实,也可以直接调用
     * @throws ParameterException
     * @return true
     */
    public function goCheck() {
        $params = request()->param();
        if (!$this->check($params)) {
            return $this->error;
        }
        return true;
    }

    /**
     * @param array $arrays 通常传入request.post变量数组
     * @return array 按照规则key过滤后的变量数组
     * @throws ParameterException
     */
    public function getDataByRule($arrays) {
        if (array_key_exists('user_id', $arrays) | array_key_exists('uid', $arrays)) {
            return '参数中包含有非法的参数名user_id或者uid';
        }
        $newArray = [];
        foreach ($this->rule as $key => $value) {
            $newArray[$key] = $arrays[$key];
        }
        return $newArray;
    }

    protected function isPositiveInteger($value, $rule = '', $data = '', $field = '') {
        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
            return true;
        }
        return $field . '必须是正整数';
    }

    protected function isNotEmpty($value, $rule = '', $data = '', $field = '') {
        if (empty($value)) {
            return $field . '不允许为空';
        } else {
            return true;
        }
    }

    //没有使用TP的正则验证,集中在一处方便以后修改
    //不推荐使用正则,因为复用性太差
    //手机号的验证规则
    protected function isMobile($value) {
        $rule = '^1(3|4|5|7|8)[0-9]d{8}$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

}
 

 

很赞哦! (0)

文章评论

    高端网站建设