## 設置規則
~~~
namespace app\models\validate;
class customers extends \lib\_model{
protected $tb = 'customers';
public $validate = [
'nickname'=> 'not_empty',
'bron_date'=> 'not_empty',
'tel'=> 'not_empty|phone',
'number'=> 'not_empty|uniqid:customers,number',
'text'=> 'not_empty',
];
~~~
## 規則定義
規則定義支持下面方式:
~~~
public $validate = [
'nickname'=> 'not_empty',
'bron_date'=> 'not_empty',
'tel'=> 'not_empty|phone',
'number'=> 'not_empty|uniqid:customers,number',
'text'=> 'not_empty',
];
~~~
對于一個字段可以設置多個驗證規則,使用`|`分割。
## 屬性定義
通常情況下,我們實際在定義驗證類的時候,可以通過屬性的方式直接定義驗證規則等信息,例如:
~~~
namespace app\models\validate;
class customers extends \lib\_model{
protected $tb = 'customers';
public $validate = [
'nickname'=> 'not_empty',
'bron_date'=> 'not_empty',
'tel'=> 'not_empty|phone',
'number'=> 'not_empty|uniqid:customers,number',
'text'=> 'not_empty',
];
public $messages = [
'nickname'=>[
'not_empty'=>'姓名不能為空',
],
'bron_date'=>[
'not_empty'=>'生日不能為空',
],
'tel'=>[
'not_empty'=>'電話不能為空',
'phone'=>'電話號碼格式錯誤',
],
'number'=>[
'not_empty'=>'卡號不能為空',
'uniqid'=>'卡號必須是唯一的',
],
'text'=>[
'not_empty'=>'興趣愛好不能為空',
]
];
}
~~~
>[info]如果你想添加新的驗證規則,可在該文件內添加`framework/core/validator.php`
eg:手機號驗證
/**
* 手機號
* @param [type] $input
* @return [type]
*/
static function phone($input)
{
return !empty($input) && preg_match('/^[+]?([\d]{0,3})?[\(\.\-\s]?(([\d]{1,3})[\)\.\-\s]*)?(([\d]{3,5})[\.\-\s]?([\d]{4})|([\d]{2}[\.\-\s]?){4})$/', $input);
}