验证器验证
<?php
namespace app\index\validate;
use think\Validate;
class Cate extends Validate
{
/**
* 验证规则
* @var array
*/
protected $rule=[
'catename'=>'unique:cate|require|max:25',
];
/**
* 错误提示信息
* @var array
*/
protected $message=[
'catename.require'=>'栏目名称不得为空!',
'catename.unique'=>'栏目名称不得重复!',
];
/**
* 验证场景
* @var array
*/
protected $scene=[
'add'=>['catename'],
'edit'=>['catename'],
];
}
控制器
public function add()
{
// 实例化模型
$cate = new CateModel();
// 判断是否是POST提交数据
if ($this->request->isPost()) {
// 获得post提交过来的数据
$data = Request::post();
// 实例化验证器
$validate = new \app\index\validate\Cate;
// 验证器验证
if (!$validate->scene('add')->check($data)) {
$this->error($validate->getError());
}
// 数据添加 返回 1 或者 0
$add = $cate->save($data);
if ($add) {
$this->success('添加栏目成功!', url('index/cate/lst'));
} else {
$this->error('添加栏目失败!');
}
}
// 调用模型的 catetree 拿到数据
$cateres = $cate->catetree();
// 对页面进行赋值
$this->assign('cateres', $cateres);
return $this->fetch();
}
独立验证
// 用用户的添加
public function userAdd(Request $request,Validate $validate)
{
$data = $request->param();
$status = 1;
$message = "添加成功";
$validate->rule([
'uname|用户名' => "require",
'upass|密码' => "require|min:6|max:32",
'urealname|真实姓名' => "require",
'utel|电话' => 'require|mobile',
'uemail|邮箱' => 'require|email',
'uaddress|地址' => "require",
]);
if (!$validate->check($data)) {
return ['status' => 0, 'message' => $validate->getError()];
} else {
$user = UserModel::create($data);
if ($user === null) {
$status = 0;
$message = '添加失败';
}
}
addLog("添加了用户");
return ['status' => $status, 'message' => $message];
}
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!