在本模块下新建一个validate目录,新建一个User.php,这个就是User验证器。
~~~
<?php
namespace app\admin\validate;
use think\Validate;
class User extends Validate
{
protected $rule = [
'user_name' => 'require|max:12',
'user_password' => 'require|max:30',
];
protected $message = [
'user_name.require' => '名称必须',
'user_name.max' => '名称最多不能超过12个字符',
'user_password.require' => '密码必须',
'user_password.max' => '密码最多30个字符',
];
}
~~~
使用的时候先载入验证器,然后将验证数组传入:
~~~
//获取用户输入
$new_user['user_name'] = Request::instance()->post('user_name');
$new_user['user_password'] = Request::instance()->post('user_password');
$new_user['user_encrypt'] = Request::instance()->post('user_encrypt');
//验证表单
$validate_new_user = Loader::validate('User');
$validate_new_user->check($new_user);
if($validate_new_user->getError()){
return $validate_new_user->getError();
exit;
}else {.....
~~~