tp6 验证 validate 用法
程序员文章站
2024-03-22 09:53:40
...
例子:给后端用户定义一个专属的验证类 User
1.定义规则和提示文字 User.php代码
<?php
namespace app\admin\validate;
use think\Validate;
class User extends Validate
{
protected $rule = [
'username' => 'require|chsAlphaNum|length:6,30',
'password' => 'require|length:6,30',
'verifyCode' => 'require|length:4',
'email' => 'email',
'tel' => 'mobile|number|length:11',
];
protected $message = [
'username.require' => '用户名必须填写',
'username.chsAlphaNum' => '用户名长度范围6-30个字符',
'username.length' => '用户名只能是汉字、字母和数字',
'password.require' => '密码必须填写',
'password.length' => '密码必须6-30个字符',
'verifyCode.require' => '验证码必须填写',
'verifyCode.length' => '验证码必须5位',
'tel.mobile' => '填写有效的手机',
'tel.number' => '手机只能数字',
'tel.length' => '手机只能11位数字',
'email' => '邮箱格式错误',
];
}
2.控制器引用
要引用
use app\admin\validate\User;
use think\exception\ValidateException;
<?php
namespace app\admin\controller;
use think\facade\View;
// use think\db\Where;
use think\facade\Env;
use app\admin\validate\User;
use think\exception\ValidateException;
class Login
{
public function index()
{
return View::fetch();
}
public function login()
{
// $where = new Where;
$sdf=env('CMS_PWD');
// var_dump($sdf);exit;
$username=input('post.username/s');
$password=input('post.password');
$verifyCode=input('post.verifyCode/s');
// $username=input('post.username/s');
try {
//验证
validate(User::class)->check([
'username' => $username,
'password' => $password,
'verifyCode' => $verifyCode,
]);
if (request()->isAjax()){
$rs = Db::name('admin')
->field('username,password,realname,nickname,img,tel,email,department_id,department_id2,role_id,group_id,code_md5,enterprise_id')
->where($where)
->find();
}else{
throw new \Exception("非法提交");
}
$code=200;$msg='成功';
} catch (ValidateException $e) {
return ['code'=>-200,'msg'=>$e->getError()];
} catch (\Exception $e) {
// 这是进行异常捕获
return ['code'=>-200,'msg'=>$e->getMessage()];
}
return json(['code' => $code,'msg' =>$msg]);
}
}