为什么要对数据验证呢?写后台的永远不要相信前端给的数据,一定要对前端给过来的数据进行验证!!!
控制器:
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function index()
{
$data = [
'name'=>'1234544444444444444444444',
'email'=>'thinkphp@qq.com',
'age'=>'10'
];
// $validate = Loader::validate('User');
$validate = validate('User');
if(!$validate->check($data)){
// dump($validate->getError());
$msk = $validate->getError();
return json(['message'=>$msk]);
}
return json($data);
}
}
验证器:
<?php
namespace app\index\validate;
use think\Validate;
class User extends Validate
{
protected $rule = [
'name' => 'require|max:5',
'email' => 'email',
'age' => 'number|between:1,120',
];
protected $message = [
'name.require' => '名称必须',
'name.max' => '名称最多不能超过25个字符',
'age.number' => '年龄必须是数字',
'age.between' => '年龄只能在1-120之间',
'email' => '邮箱格式错误',
];
}