Tp-validate进阶

时间:2023-03-08 23:33:12
Tp-validate进阶

Tp-validate进阶

阶段1:基础

application/controller/v1/Banner.php

<?php
namespace app\api\controller\v1;
use think\Controller;
use think\validate; class Banner extends controller{
public function index(){
//http://localhost/thinkphp5/public/index.php/api/v1.Banner/index }
public function getBanner(){ $data=array(
'name'=>'dash',
'email'=>'wolichihua2011@163.com' );
//独立验证
$validate=new Validate([ 'name'=>'require|max:10',
'email'=>'email'
]); //batch()批量验证 否则只返回最后一个getError验证信息
$result=$validate->batch()->check($data);//返回布尔
var_dump($result);
var_dump($validate->getError());//返回错误信息 } }

阶段二:讲=将验证规则单独放到其他的类文件中

<?php
namespace app\api\controller\v1;
use think\Controller;
use think\validate;
//use app\api\validate\TestValidate;
class Banner extends controller{
public function index(){
//http://localhost/thinkphp5/public/index.php/api/v1.Banner/index
}
public function getBanner($id){ $data=array(
'name'=>'dash',
'email'=>'wolichihua2011@163.com' ); //验证器 直接new
$validate= new \app\api\validate\TestValidate(); //或者引入命名空间在new use app\api\validate\TestValidate (application/api/validate/TestValidate.php)
   $validate= new TestValidate();//必须有这个命名空间 use app\api\validate\TestValidate
//batch()批量验证 否则只返回最后一个getError验证信息
$result=$validate->batch()->check($data);//返回布尔
var_dump($result);
var_dump($validate->getError());//返回错误信息 } }
application/api/validate/TestValidate.php
<?php
namespace app\api\validate;
use think\Validate;
class TestValidate extends Validate{
protected $rule =[
'name'=>'require|max:10',
'email'=>'email' ];
}

阶段三:封装验证参数:

application/controller/v1/Banner.php

<?php
namespace app\api\controller\v1;
use think\Controller;
use think\validate;
use app\api\validate\IDMustBePositiveInt;
class Banner extends controller{
public function index(){
http://localhost/thinkphp5/public/index.php/api/v1.Banner/index
}
public function getBanner($id){ (new IDMustBePositiveInt())->goCheck(); } }

application/api/validate/BaseValidate.php

<?php
namespace app\api\validate;
use think\Request;
use think\Validate;
use think\Exception;
class BaseValidate extends Validate{
public function goCheck(){
// 获取http参数
// 对这些参数做检验
$request= Request::instance();
$params=$request->param();
$result=$this->check($params);
if (!$result) {
$error=$this->error;
throw new Exception($error, 1); }else{
return true;
}
}
}

application/api/validate/IDMustBePositiveInt.php

<?php
namespace app\api\validate;
class IDMustBePositiveInt extends BaseValidate{
protected $rule=array( 'id'=>'require|isPositiveInteger'
); //自定义验证规则
protected function isPositiveInteger($value, $rule='', $data='', $field='')
{
if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
return true;
}
return $field . '必须是正整数';
}
}

阶段4:讲自定义规则挪到BaseValidate.php中,其他自定义的也一样只保留rule规则就行了

阶段5:创建更多的自定义验证类

阶段六:自定义验证类文件多了,就需要工厂类来封装啦!