我們在使用thinkphp6中的數據驗證時,如果使用不多的話,會經常遇到校驗不對,在這個小問題上折騰很多,索引就不用了。我還不如直接寫if條件來的迅捷!!
下面把常見的校驗方法進行一下整理:
protected $regex = ['float_two' => '/^[0-9]+(.[0-9]{1,2})?$/', //兩位小數點'phone' => '/^1[3456789]\d{9}$/', //手機號
];/*** 定義驗證規則* 格式:'字段名' => ['規則1','規則2'...]** @var array*/protected $rule = ['id' => 'require|gt:0', //大于0'phone' => 'require|regex:phone', //手機號'type' => ['require', 'In:0,1,2'], //必須是0、1、2中的一個'order_id' => ['require','length'=>'1,32','alphaNum'], //1-32位字母數字'total_price' => ['require','float'], //金額,浮點數'sort' => 'require|number', //數字'region_info' => 'array', //數組'sort' => 'number' //數字'account' => ['require', 'alphaDash'], //字母數字下劃線,破折號'real_name|管理員姓名' => 'require|max:16','account|賬號' => 'require|max:16|min:4','phone|聯系電話' => 'isPhone', //自定義函數'image|分類圖片' => 'max:128','is_banner|是否為Banner' => 'require|integer''status|狀態' => 'require|in:0,1','phone' => 'require|number|mobile','integral_user_give|邀請好友贈送積分' => 'require|integer|>=:0','integral_community_give|發布種草可獲得積分' => 'require|number|egt:0|elt:9999','undelives|不配送區域信息'=>'requireIf:undelivery,1|Array|undelive', //這是哪個高手寫的,這么復雜,我也沒看懂'full_reduction|滿贈金額' => 'requireIf:send_type,1|float|>=:0','coupon_time|有效期限' => 'requireIf:coupon_type,0|integer|>:0',];//定義不同驗證的提示信息,這個很簡單,一般不會出錯!protected $message = ['meal_id.require' => '請傳入套餐id','meal_id.number' => '套餐id必須為數字','price.require' => '請填寫套餐金額','num.require' => '請填寫購買數量','num.number' => '購買數量必須為數字','type.require' => '請填寫購買套餐類型'];//校驗手機號 , 這里的data指的是全部的參數,自定義的可以和其它參數做比較protected function isPhone($val,$data){if ($val && !preg_match('/^1[3456789]{1}\d{9}$/', $val))return '請輸入正確的手機號';elsereturn true;}//驗證場景 ,變量的方式,這里說明 login只驗證密碼和賬號, phone只驗證手機號protected $scene = ['login' => ['password', 'account'],'phone' => ['phone']];//函數的方法public function sceneSave(){return $this->only(['realname','phone','address','province','city','district']);}
如何使用:
try{$this->validate(TrailValidate::class)->scene('apply')->check($data);
}catch(\Exception $e){return app('json')->fail($e->getMessage());
}
TrailValidate::class 是你的校驗類,放哪里自己定。
scene('apply')? ,apply是你的場景。
check($data) ;? $data是你要校驗的數據。
注意:驗證場景有兩種寫法以,一種是數組,一種是函數。
當使用函數時必須是: scene+場景名(Save) 首字母大寫,如果直接寫場景名是識別不到的!。
以上rule匯總自多個開源系統,用來做備忘和大家共勉!
如果你有其它想法我們可以共同探討!