批改状态:未批改
老师批语:
主题:
自己写一个验证器,并在控制器中进行调用。
实例内容:
使用验证器验证模拟数据是否符合自定义规则。
效果图:
1.验证器

2.简化版

3.绕过验证器

<?php
// 创建模型的命名空间,对应路径
namespace app\index\model;
// 引入框架模型类
use think\Model;
// 引入软删除trait
use think\model\concern\SoftDelete;
// 创建模型类,由于框架模型类是抽象类无法实例化,这里创建的模型类需要继承框架的模型类才能使用框架模型类中的方法
class Car extends Model
{
// 在模型类中引入软删除类
use SoftDelete;
// 创建模型类的方法,变量需要私有化,此处的变量$table和$pk是框架预定义的
protected $table = 'car';
protected $pk = 'car_id';
// 软删除时间
protected $deleteTime = 'delete_time';
// 默认软删除字段默认值
protected $defaultSoftDelete = 0;
// 自动时间戳:需要开启框架自动时间戳设置\config\database.php
protected $autoWriteTimestamp = true;
// 绑定新增和更新时间字段名
protected $createTime = 'create_time';
protected $updateTime = 'update_time';
}点击 "运行实例" 按钮查看在线实例
<?php
// 验证器命名空间
namespace app\validator;
// 引入框架验证器
use think\Validate;
class Car extends Validate
{
// 设置验证器规则,详见手册
protected $rule = [
'car_name' => 'require|length:1,25',
'car_type' => 'require',
'car_color' => 'require|length:2,25',
'price' => 'number|min:5',
];
// 自定义错误信息,如果不自定义将使用系统默认信息
protected $message = [
'car_name.require' => '名称必须',
'car_name.length' => '名称长度必须在1~25个字符之间',
'car_type.require' => '车辆类型必须',
'car_color.require' => '颜色必须',
'car_color.length' => '颜色名称长度必须在2~25个字符之间',
'price.number' => '价格必须是数字',
'price.min' => '价格最小长度为5',
];
}点击 "运行实例" 按钮查看在线实
<?php
namespace app\index\controller;
use think\Controller;
// 引入框架验证器类
use think\Validate;
// 引入用户验证器类
use app\validator\Car;
class Verify extends Controller
{
// 验证器方法
public function checkcar() {
// 模拟需要验证的表数据
$data = [
'car_name'=>'英菲尼迪',
'car_type' => '阿西吧',
'car_color' => '蓝色',
'price' => '我',
];
$check = new Car();
if(!$check->check($data)) {
// 这里错误信息优先显示用户自定义的
dump($check->getError());
} else {
return 'PASS';
}
}
// 验证器简化
public function checkcar1() {
// 模拟需要验证的表数据
$data = [
'car_name' => '',
'car_type' => '阿西吧',
'car_color' => '蓝色',
'price' => 1111111,
];
$rule = 'app\validator\Car';
$res = $this->validate($data, $rule);
if(true !== $res) {
return $res;
} else {
return 'PASS';
}
// 在控制器中直接验证,绕过验证器
// 模拟需要验证的表数据
// $data = ['car_name' => '20'];
// 验证规则
// $rule = ['car_name' => 'between:5,25'];
// 输出信息自定义
// $msg = ['car_name.between' => '名称必须在5~25之间'];
// $res = $this->validate($data, $rule, $msg);
// 验证
// if(true !== $res) {
// return $res;
// } else {
// return 'PASS';
// }
}
}点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号