TP內置驗證功能提供兩種驗證方法
- 驗證器(推薦)
$validate = Validate::make([ 'id' => 'require|integer', ]); if ($validate->check(['id' => $id])) { }
優點: 方便、快捷
缺點: 可讀性和擴展性差
- 獨立驗證
namespace app\admin\validate; class Banner extends BaseValidate { protected $rule = [ 'name' => 'require|max:25', 'age' => 'number|between:1,120', 'email' => 'email', ]; protected $message = [ 'name.require' => '名稱必須', 'name.max' => '名稱最多不能超過25個字符', 'age.number' => '年齡必須是數字', 'age.between' => '年齡只能在1-120之間', 'email' => '郵箱格式錯誤', ]; protected $scene = [ 'edit' => ['name','age'], ]; }
官方提供了一些驗證規則,如果不能滿足需求可以自定義
建議自定義在驗證器基類中,這樣所有繼承這個類的子驗證器都可以使用這些驗證方法
定義規則
protected function isMobile($value) { $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^'; $result = preg_match($rule, $value); if ($result) { return true; } else { return false; } }
自定義驗證器有以下幾個參數
value:待驗證的值
field:驗證字段名
驗證器推薦使用方法
定義驗證器基類,繼承 Validate類 ,在基類中定義一些公共驗證規則和方法
<?php namespace app\admin\validate; use think\Validate; /** * Class BaseValidate * 驗證類的基類 */ class BaseValidate extends Validate { /** * 檢測所有客戶端發來的參數是否符合驗證類規則 * 基類定義了很多自定義驗證方法 * 這些自定義驗證方法其實,也可以直接調用 * @throws ParameterException * @return true */ public function goCheck() { $params = request()->param(); if (!$this->check($params)) { return $this->error; } return true; } /** * @param array $arrays 通常傳入request.post變量數組 * @return array 按照規則key過濾后的變量數組 * @throws ParameterException */ public function getDataByRule($arrays) { if (array_key_exists('user_id', $arrays) | array_key_exists('uid', $arrays)) { return '參數中包含有非法的參數名user_id或者uid'; } $newArray = []; foreach ($this->rule as $key => $value) { $newArray[$key] = $arrays[$key]; } return $newArray; } protected function isPositiveInteger($value, $rule = '', $data = '', $field = '') { if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) { return true; } return $field . '必須是正整數'; } protected function isNotEmpty($value, $rule = '', $data = '', $field = '') { if (empty($value)) { return $field . '不允許為空'; } else { return true; } } //沒有使用TP的正則驗證,集中在一處方便以后修改 //不推薦使用正則,因為復用性太差 //手機號的驗證規則 protected function isMobile($value) { $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^'; $result = preg_match($rule, $value); if ($result) { return true; } else { return false; } } }