tp框架使用validate驗證器
阿新 • • 發佈:2018-12-17
檔案目錄
index.php
<?php namespace app\index\controller; use app\index\validate\User; use think\Controller; use think\Request; class Index extends Controller { public function index() { if(request()->isPost()) { $data=[ 'name'=>input('name'), 'pwd'=>input('pwd'), ]; $validate = new User(); $result = $validate->scene('edit')->check($data); if (!$validate->check($data)) { $this->error($validate->getError()); } } else { return $this->fetch('index'); } } }
user.php
<?php namespace app\index\validate; use think\Validate; class User extends Validate { protected $rule =[ 'name' => 'require|max:8|require|min:2', 'pwd' => 'require|max:16|require|min:4', ]; protected $message = [ 'name.require' => '使用者姓名不能為空', 'name.max' => '使用者姓名最大長度為8', 'name.min' => '使用者姓名最小長度為2', 'pwd.require' => '密碼不能為空', 'pwd.max' => '密碼最長字元為6', 'pwd.min' => '密碼最短長度為4', ]; protected $scene = [ 'edit' => ['name','pwd'], ]; } ?>
index.html
</!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8"> </head> <body> <form method="post" action="{url:index/index}"> 姓名:<input type="text" name="name"><br/> 密碼:<input type="password" name="pwd"><br/> <input type="hidden" name="hid"> <input type="submit" name="sub" value="提交"> </form> </body> </html>