abstrait:驗證器練習(xí)代碼: <?php /** * Created by PhpStorm. * User: Administrator * Date: 2019/4/19 * Time: 14:09 */ namespace app\val
驗證器練習(xí)代碼: <?php /** * Created by PhpStorm. * User: Administrator * Date: 2019/4/19 * Time: 14:09 */ namespace app\validate; use think\Validate; class Staff extends Validate { //驗證規(guī)則 protected $rule =[ 'name' => 'require|length:4,20', 'sex' => 'in:0,1', 'age' => 'require|between:18,60', 'salary' => 'require|gt:1500' ]; //自定義錯誤信息 protected $message = [ 'name.require'=>'員工姓名不能為空', 'name.length'=>'姓名不符合規(guī)定', 'sex.in'=>'性別為男或者女', 'age.require'=>'年齡不能為空', 'age.between'=>'年齡不符合規(guī)定', 'salary.require'=>'工資不能為空', 'salary.gt'=>'工資不能低于社平工資' ]; } 控制器中代碼: <?php /** * Created by PhpStorm. * User: Administrator * Date: 2019/4/19 * Time: 14:16 */ namespace app\index\controller; //命名空間 use think\Controller; //繼承控制器 use app\validate\Staff; //導(dǎo)入驗證器類 use think\Validate; //導(dǎo)入框架的驗證器類 class Verify extends Controller { //驗證器驗證 public function demo1() { //準(zhǔn)備驗證的數(shù)據(jù) $data =[ 'name'=>'lyu', 'sex'=>0, 'age'=>40, 'salary'=>2000 ]; //驗證規(guī)則 $validate = new Staff(); if(!$validate->check($data)) { dump($validate->getError()); }else{ return '驗證通過'; } } //驗證器的簡化操作:$this->validate($data,$rule,$mess) public function demo2() { //準(zhǔn)備驗證的數(shù)據(jù) $data =[ 'name'=>'lyudddd', 'sex'=>0, 'age'=>46, 'salary'=>2000 ]; //準(zhǔn)驗證規(guī)則 $rule = 'app\validate\Staff'; $res = $this->validate($data,$rule); if(true !== $res){ return $res; } return '驗證成功'; } //當(dāng)前控制器直接驗證 public function demo3() { //準(zhǔn)備數(shù)據(jù) $data =['age'=>20]; //驗證條件 $rule = ['age'=>'between:10,50']; //提示信息 $message =['age.between'=>'年齡必須在10到50之家']; //驗證操作 $res = $this->validate($data,$rule,$message); if(true !== $res){ return $res; } return '驗證成功'; } //獨(dú)立驗證 public function demo4() { //調(diào)用think\Validate.php,用Validate::make()創(chuàng)建驗證規(guī)則并返回驗證對象 //$validate->check($data)驗證 //1.創(chuàng)建驗證規(guī)則 $rule = ['age'=>'require|between:30,60']; //2.錯誤信息 $message =['age.require' =>'年齡必須填寫' , 'age.between'=>'年齡必須在10到50之間']; //3.創(chuàng)建數(shù)據(jù) $data = ['age'=>50]; //4.執(zhí)行Validate::make() $validate = Validate::make($rule,$message); $res = $validate->check($data); return $res ? '驗證通過' : $validate->getError(); } }
Professeur correcteur:西門大官人Temps de correction:2019-04-20 13:07:09
Résumé du professeur:系統(tǒng)一般會對用戶輸入的數(shù)據(jù)進(jìn)行校驗,可以手工校驗,也可以寫驗證器校驗。