ThinkPHP开发技巧集锦(一):使用validate构建参数验证层

普通使用

$data = [
            'id' => $id
        ];

       $validate = new Validate([
            'id' => 'require|max:10',

        ]);
      
$result = $validate->batch()->check($data);

var_dump($validate->getError());

高级使用:(推荐)

自定义验证规则

BaseValidate.php

class BaseValidate extends Validate
{

    public function goCheck()
    {
        //get the params
        $request = Request::instance();
        $params = $request->param();

        $request = $this->check($params);
        if (!$request){
            $error = $this->error;
            throw new Exception($error);
        }else{
            return true;
        }
    }

}

2、 IDMustBePositiveInt.php继承BaseValidate

class IDMustBePositiveInt extends BaseValidate

{

    protected $rule = [
        'id' => 'require|isPositiveInteger'
    ];

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

    }

}

3、使用

 (new IDMustBePositiveInt())->goCheck();//直接验证

 

你可能感兴趣的:(ThinkPHP开发技巧集锦,ThinkPHP开发技巧集锦)