thinkphp验证器

验证器类:$validate=new \think\Validate($rule,$message,$field);  注意:开启表单令牌后需要验证它哦

独立验证:

//独立验证
$rule=[
    'name'  => 'require|max:25',
    'email' => 'email'
]
$msg=[
    'name.require' => '名称必须',
    'name.max'     => '名称最多不能超过25个字符',
    'email'        => '邮箱格式错误',    
];
$field = [
    'name'  => '名称',
    'email' => '邮箱',    
];
$validate = new Validate($rule,$msg,$field); 
$data = [
    'name' => 'thinkphp',
    'email' => 'thinkphp@qq.com'
]; 
if (!$validate->check($data)) {
    dump($validate->getError());
}

 

make、rule、extend、setTypeMsg、message、scene、hasscene、batcch、check、getError

验证器:定义在模块下的validate文件夹内;

注意:Call to undefined function mb_strlen() :开启:extension=php_mbstring.dll; 还不行就就看看这extension_dir = "ext";还不行就绝对路径

 

前台页面

<form action="{:url('addFormData')}" method="post">
    <input type="text" name="name" value="thinkphp">
    <input type="text" name="email" value="thinkphp@qq.com">
    <input type="text" name="zip" value="888888">
    <input type="text" name="age" value="20">
    <input type="text" name="status" value="2">
    {:token('__token__', 'sha1')}
    <input type="submit" value="提交">
</form>

控制器:

<?php
namespace app\index\controller;
use think\Controller;
class Test extends Controller{

    public function index()
    {
        
        return $this->fetch('index@/Test/index');
    }


    public function addFormData(\think\Request $request)
    {

        $name=$request->post('name');
        $email=$request->post('email');
        $zip=$request->post('zip');
        $age=$request->post('age');
        $status=$request->post('status');
        $token=$request->post('__token__');
        

        $data = [
            'name'=>$name,
            'email'=>$email,
            'zip'=>$zip,
            'age'=>$age,
            'status'=>$status,
            '__token__'=>$token
        ];

        $validate = \think\Loader::validate('test');//or  $validate = validate('test');
        //实例化后还可以动态添加规则 他将合并到Test验证rule属性里
        $validate->rule([
            'zip'   => '/^\d{6}$/',
            'status'=> 'number|between:0,2'
        ]);
        //实例化后还可以动态添加错误信息 他将合并到Test验证$message属性里
        $validate->message([
            'zip'=>'邮编格式不正确',
            'status.between'=>'状态超出取值范围',
            'status.number'=>'状态数据类型错误',
        ]);
     //实例化后可以动态添加自定义的验证字段描述
        $validate->addField([
            'zip'=>'邮编',
            'status'=>'状态',
        ]);

        if(!$validate->check($data)){
            dump($validate->getError());
        }        
    }
}

验证器:

<?php
namespace app\index\validate;

use think\Validate;

class Test extends Validate
{
    //定义验证规则   |和数组都可以
    protected $rule = [
        'name'  =>  'require|max:25',
        'email' =>  'email',
        'age'   => ['number','between'=>'1,120'],
        '__token__'=>'token'
    ];

    //定义错误信息
    protected $message  =   [
        'name.require' => '名称必须',
        'name.max'     => '名称最多不能超过25个字符',
        'age.number'   => '年龄必须是数字',
        'age.between'  => '年龄只能在1-120之间',
        'email'        => '邮箱格式错误',    
    ];
    //定义验证字段描述
    protected $field=[
         'name'  => '名称',
        'age'   => '年龄',
        'email' => '邮箱',    
    ];

    //定义场景(后面根数组是重新定义规则)
    protected $scene = [
        'edit'  =>  ['name','email','age'=>'require|number|between:1,120'],
    ];


    /**
     * 自定义动态添加验证字段描述
     */
    public function addField($name,$field='')        
    {
        if (is_array($name)) {
            $this->field = array_merge($this->field, $name);
        } else {
            $this->field[$name] = $field;
        }
        return $this;
    }

}

 

 

 

THINKPHP 防止重复提交表单 自己动手制作表单令牌token 

function.php 

//创建TOKEN
function creatToken() {
    $code = chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE)) . chr(mt_rand(0xB0, 0xF7)) . chr(mt_rand(0xA1, 0xFE));
    session('TOKEN', authcode($code));
}

//判断TOKEN
function checkToken($token) {
    if ($token == session('TOKEN')) {
        session('TOKEN', NULL);
        return TRUE;
    } else {
        return FALSE;
    }
}

/* 加密TOKEN */
function authcode($str) {
    $key = "ANDIAMON";
    $str = substr(md5($str), 8, 10);
    return md5($key . $str);
}

html form

<form action="{:U()}" method="post"  class="form-horizontal">
    <input type="hidden" name="TOKEN" value="{:session('TOKEN')}"> 
...
</form>

1.在页面展示前调用creatToken()方法生成token。

2.在相应控制器POST请求中 使用 checkToken() 进行判断是否重复提交。

if(IS_POST){
            
            //防止重复提交 如果重复提交跳转至相关页面
            if (!checkToken($_POST['TOKEN'])) {
                 $this->redirect('index/index');
                return;
            }

            //下面相关业务代码
}else{

         //创建token
            creatToken();
            $this->display();
}

 

posted @ 2019-02-25 00:01  虚无缥缈的云  阅读(854)  评论(0编辑  收藏  举报