abstract://创建验证器User.php//创建验证器User.php
namespace app\validate;
use think\Validate;
class User extends Validate{
protected $rule = ['name' => 'require|length:4,15',
'sex' => 'in:0,1',
'age' => 'require|between:18,60',
'salary' => 'require|gt:1500'
];
protected $message = [
'name.require' => '名字不能为空',
'name.length' => '名字长度为4至15个字符之间',
'sex.in' => '姓别必需是男或女',
'age.require' => '年龄不能为空',
'age.between' => '年龄必须是18至60岁之间',
'salary.require' => '工资不能为空',
'salary.gt' => '工资不能小于1500'
];
}
namespace app\index\controller;
use think\Controller;//加载验证类
use app\validate\User;
class Varify extends Controller{
public function insert(){//验证的数据
$data = [
'name' => 'whyan',
'sex' => 5,
'age' =>35,
'salary' => 1000
];//new验证实例
$user = new User;
if(!$user->check($data)) {echo $user->getError();
}else{
echo '验证通过';
}
}
//验证器验证
public function insert(){
//验证的数据
$data = [
'name' => 'whyan',
'sex' => 5,
'age' =>35,
'salary' => 1000
];
//验证的规则$rule = 'app\validate\User';
$res = $this->validate($data,$rule);
dump($res);
}//独立验证
public function varify(){
//验证的数据
$data = [
'name' => 'whyan',
'sex' => 0,
'age' =>17,
'salary' => 1000
];//验证的规则
$rule = [
'name' => 'require|length:4,15',
'sex' => 'in:0,1',
'age' => 'require|between:18,60',
'salary' => 'require|gt:1500'
];
//验证的信息
$message = [
'name.require' => '名字不能为空',
'name.length' => '名字长度为4至15个字符之间',
'sex.in' => '姓别必需是男或女',
'age.require' => '年龄不能为空',
'age.between' => '年龄必须是18至60岁之间',
'salary.require' => '工资不能为空',
'salary.gt' => '工资不能小于1500'
];
//Validate静态验证
$res = \think\Validate::make($rule,$message);
$res->check($data);
dump($res->getError());
}
}
Correcting teacher:天蓬老师Correction time:2019-11-01 14:40:45
Teacher's summary:实际上,控制器中的验证, 也是引用了独立验证, 通过一个独之类, 对一些公用数据进行验证,可以提高效率