自定义验证规则----------验证客户端传过来的id号是否为正整数
1,首先在validate
文件夹下面新建一个IDMustBePositiveInt.php
2.IDMustBePositiveInt.php
定义验证规则
<?php
namespace app\api\validate;
use think\Validate;
//1.继承自validate类
class IDMustBePositiveInt extends Validate {
//2.定义规则id必须存在,且符合自己定义的isPositiveInteger规则
protected $rule = [
'id' => 'require|isPositiveInteger'
];
//3.自定义的isPositiveInteger规则。参数$value为要验证的变量
protected function isPositiveInteger($value, $rule = '', $data = '', $field = '') {
if (is_numeric($value) && is_integer($value + 0) && ($value + 0) > 0) {
//4.如果$value是正整数,则返回true.
return true;
} else {
//4.如果$value不是正整数,则返回错误信息.
return $field . '必须是正整数';
}
}
}
3,在控制器的方法中:
第一步获取要验证的参数,
第二步实例化验证规则对象,
第三步开始验证,
第四步得到验证结果
<?php
namespace app\api\controller\v1;
use app\api\validate\IDMustBePositiveInt;
class Banner {
/*
* 获取指定id 的banner信息
* @url /banner/:id
* @http GET
* @id banner的id
* */
public function getBanner($id) {
$data = [
'id' => $id
];
$validate = new IDMustBePositiveInt();
$result = $validate->batch()->check($data);
if ($result) {
echo '正确';
} else {
echo '错误';
}
}
}