// 实例化验证类(验证规则)Validate([验证信息],[错误信息])
$validate=new Validate(
[
'username'=>"require|length:6,12",
'password'=>"require|confirm:repassword"
],
[
'username.require'=>"用户名不存在",
'username.length'=>"长度不满足",
'password.require'=>"密码不存在",
'password.confirm'=>"两次密码不一致"
]
);
// 接收用户提交的数据
$data=input("post.");
// 进行验证
if($validate->check($data)){
// 验证正确以后
$arr['username']=$data['username'];
$arr['password']=md5($data['password']);
$arr['time']=time();
$arr['status']=$data['status'];
if (Db::table('admin')->insert($arr)) {
$this->success('添加成功');
}else{
$this->error('添加失败');
}
}else{
dump($validate->getError());
}
1.验证控制器中
// 声明命名空间
namespace app\index\validate;
// 声明验证器
use think\Validate;
/**
*
*/
class Admin extends Validate
{
// 验证器规则
protected $rule=[
'username'=>"require|length:6,12",
'password'=>"require|confirm:repassword"
];
// 验证器提示信息
protected $message=[
'username.require'=>"用户名不存在",
'username.length'=>"长度不满足",
'password.require'=>"密码不存在",
'password.confirm'=>"两次密码不一致"
];
}
?>
2.使用控制器中
public function yanzhengqi(){
// 接收数据
$data=input('post.');
// 实例化验证器
$validate=new \app\index\validate\Admin;
if($validate->check($data)){
}else{
dump($validate->getError());
}
}
$rule = [
'name' => 'require|max:25',
'age' => 'number|between:1,120',
'email' => 'email',
];
$msg = [
'name.require' => '名称必须',
'name.max' => '名称最多不能超过25个字符',
'age.number' => '年龄必须是数字',
'age.between' => '年龄只能在1-120之间',
'email' => '邮箱格式错误',
];
$data = [
'name' => 'thinkphp',
'age' => 10,
'email' => '[email protected]',
];
$validate = new Validate($rule);
$validate->scene('edit', ['name', 'age']);
$result = $validate->scene('edit')->check($data);
1.类中
namespace app\index\validate;
use think\Validate;
class User extends Validate
{
protected $rule = [
'name' => 'require|max:25',
'age' => 'number|between:1,120',
'email' => 'email',
];
protected $message = [
'name.require' => '名称必须',
'name.max' => '名称最多不能超过25个字符',
'age.number' => '年龄必须是数字',
'age.between' => '年龄只能在1-120之间',
'email' => '邮箱格式错误',
];
protected $scene = [
'edit' => ['name','age'],
];
}
2.使用
$data = [
'name' => 'thinkphp',
'age' => 10,
'email' => '[email protected]',
];
$validate = new \app\index\validate\User($rule);
$result = $validate->scene('edit')->check($data);