《PHP應用:PHP YII框架開發小技巧之模型(models)中rules自定義驗證規則》要點:
本文介紹了PHP應用:PHP YII框架開發小技巧之模型(models)中rules自定義驗證規則,希望對您有用。如果有疑問,可以聯系我們。
相關主題:YII框架
PHP應用YII的models中的rules部分是一些表單的驗證規則,對于表單驗證十分有用,在相應的視圖(views)里面添加了表單,在表單被提交之前程序都會自動先來這里面的規則里驗證,只有通過對其有效的限制規則后才能被提交,可以很有效地保證表單平安和信息的有效性.還是給大家具體說明一下:
PHP應用以下是視圖(views)部分的簡單代碼:
PHP應用
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'tag-form',
'enableAjaxValidation'=>false,
)); ?>
<div class="row">
<?php echo $form->labelEx($model,'tagname'); ?>
<?php echo $form->textField($model,'tagname',array('size'=>20,'maxlength'=>32)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'tagtype'); ?>
<?php echo $form->radioButtonList($model,'tagtype'array(1=>"普通TAG",2=>"系統默認TAG"),array('separator'=>'','labelOptions'=>array('class'=>'tagtypelabel'))); ?>
</div>
<?php echo $form->errorSummary($model); ?>
<div class="row buttons">
<?php echo CHtml::submitButton($model->isNewRecord ? '添加' : '修改'); ?>
</div>
<?php $this->endWidget(); ?>
PHP應用模型(models)中rules部分的簡單代碼:
PHP應用
public function rules()
{
return array(
array('tagname,tagtype', 'required'),
array('tagtype', 'numerical', 'integerOnly'=>true),
array('tagname', 'length', 'max'=>32),
array('tagname', 'match', 'pattern'=>'/^[\x{4e00}-\x{9fa5}A-Za-z0-9]+$/u',
'message'=>'標簽不合法,必須為漢字、字母或者數字!'),
array('tagname', 'checktagname', 'on'=>'create,update'),//插入TAG時檢查是否已經存在該tag
array('tagid, tagname, tagtype', 'safe', 'on'=>'search'),
);
}
PHP應用系統默認有這些驗證規則:
PHP應用boolean : CBooleanValidator 的別名, 確保屬性的值是CBooleanValidator::trueValue 或 CBooleanValidator::falseValue .?
captcha : CCaptchaValidator 的別名,確保了特性的值等于 CAPTCHA 顯示出來的驗證碼.?
compare : CCompareValidator 的別名, 確保了特性的值等于另一個特性或常量.?
email : CEmailValidator 的別名,確保了特性的值是一個有效的電郵地址.?
default : CDefaultValueValidator 的別名, 為特性指派了一個默認值.?
exist : CExistValidator 的別名, 確保屬性值存在于指定的數據表字段中.?
file : CFileValidator 的別名, 確保了特性包含了一個上傳文件的名稱.?
filter : CFilterValidator 的別名, 使用一個filter轉換屬性.?
in : CRangeValidator 的別名, 確保了特性出現在一個預訂的值列表里.?
length : CStringValidator 的別名, 確保了特性的長度在指定的范圍內.?
match : CRegularExpressionValidator 的別名, 確保了特性匹配一個正則表達式.?
numerical : CNumberValidator 的別名, 確保了特性是一個有效的數字.?
required : CRequiredValidator 的別名, 確保了特性不為空.?
type : CTypeValidator 的別名, 確保了特性為指定的數據類型.?
unique : CUniqueValidator 的別名, 確保了特性在數據表字段中是唯一的.?
url : CUrlValidator 的別名, 確保了特性是一個有效的路徑.
PHP應用基本上還是比較全面的,一般的都夠用了,但是還是有時候有的驗證需要自定義.就以上面的代碼為例,我們在添加TAG時需要檢查系統之前是否已經存在這個TAG,如果存在則不讓用戶添加.這個就需要在添加之前去查詢數據庫,看該TAG是否已經存在,這里我們就需要自定一個驗證規則了.
PHP應用關鍵有一下兩個步驟:
PHP應用1、在rules中 添加代碼:array('tagname', 'checktagname', 'on'=>'create,update'),//插入TAG時檢查是否已經存在該tag
PHP應用注:我在其中用了 'on'=>'create,update',所以這個驗證規則之對create,update場景生效
PHP應用2、在該模型(models)中添加驗證函數:
PHP應用
public function checktagname($attribute,$params){
$oldtag = Tag::model()->findByAttributes(array('tagname'=>$this->tagname));
if($oldtag->tagid > 0){
$this->addError($attribute, '該TAG已經存在!');
}
}
PHP應用其中需要說明的是:
PHP應用(1)該驗證函數的參數必須是($attribute,$params),不能缺少其中任何一個;
PHP應用(2)$this->addError($attribute, '該TAG已經存在!');這個是你想要在視圖中輸出的錯誤提示信息.
PHP應用就是這么簡單,有了這個辦法,表單驗證的各種想要的規則就都可以自定義了.
PHP應用下面給大家介紹Yii自定義驗證規則
PHP應用最簡單的定義驗證規則的辦法是在使用它的模型(model)內部定義.
PHP應用比方說,你要檢查用戶的密碼是否足夠平安.
PHP應用通常情況下你會使用 CRegularExpression 辦法驗證,但為了本指南,我們假設不存在此驗證辦法.
PHP應用首先在模型(model)中添加兩個常量
PHP應用const WEAK = 0;
const STRONG = 1;然后在模型(model)的 rules 辦法中設置:
PHP應用
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
return array(
array('password', 'passwordStrength', 'strength'=>self::STRONG),
);
}
PHP應用確保你寫的規則不是一個已經存在的規則,否則將會報錯.
PHP應用現在要做的是在模型(model)中創建一個名稱為上面填寫的規則的辦法(即 passwordStrength).
PHP應用
/**
* check if the user password is strong enough
* check the password against the pattern requested
* by the strength parameter
* This is the 'passwordStrength' validator as declared in rules().
*/
public function passwordStrength($attribute,$params)
{
if ($params['strength'] === self::WEAK)
$pattern = '/^(?=.*[a-zA-Z0-9]).{5,}$/';
elseif ($params['strength'] === self::STRONG)
$pattern = '/^(?=.*\d(?=.*\d))(?=.*[a-zA-Z](?=.*[a-zA-Z])).{5,}$/';
if(!preg_match($pattern, $this->$attribute))
$this->addError($attribute, 'your password is not strong enough!');
}
PHP應用剛才創建的辦法需要兩個參數:* $attribute 需要驗證的屬性* $params 在規則中自定義的參數
PHP應用在模型的 rules 辦法中我們驗證的是 password 屬性,所以在驗證規則中需要驗證的屬性值應該是 password.
PHP應用在 rules 辦法中我們還設置了自定義的參數 strength,它的值將會放到 $params 數組中.
PHP應用你會發現在辦法中我們使用了 CModel::addError().
PHP應用添加錯誤接受兩個參數:第一個參數是在表單中顯示錯誤的屬性名,第二個參數時顯示的錯誤信息 .
PHP應用完整的辦法:繼承 CValidator 類
PHP應用如果你想把規則使用在多個模型(model)中,最好的辦法時繼承 CValidator 類.
PHP應用繼承這個類你可以使用像 CActiveForm::$enableClientValidation (Yii 1.1.7 版本后可用) 類似的其他功能.
PHP應用創建類文件
PHP應用首先要做的是創建類文件.最好的辦法時類的文件名和類名相同,可以使用 yii 的延遲加載(lazy loading)功能.
PHP應用讓我們在應用(application)的擴展(extensiions)目錄(在 protected 文件夾下)下新建一個文件夾.
PHP應用將目錄命名為: MyValidators
PHP應用然后創建文件: passwordStrength.php
PHP應用在文件中創建我們的驗證辦法
PHP應用
class passwordStrength extends CValidator
{
public $strength;
private $weak_pattern = '/^(?=.*[a-zA-Z0-9]).{5,}$/';
private $strong_pattern = '/^(?=.*\d(?=.*\d))(?=.*[a-zA-Z](?=.*[a-zA-Z])).{5,}$/';
...
}
PHP應用在類中創建屬性,此屬性為在驗證規則中使用的參數.
PHP應用CValidator 會自動根據參數來填充這些屬性.
PHP應用我們也創建了兩個其他的屬性,它們為 preg_match 函數使用的正則表達式.
PHP應用現在我們應該重寫父類的抽象辦法(abstract method) validateAttribute
PHP應用
/**
* Validates the attribute of the object.
* If there is any error, the error message is added to the object.
* @param CModel $object the object being validated
* @param string $attribute the attribute being validated
*/
protected function validateAttribute($object,$attribute)
{
// check the strength parameter used in the validation rule of our model
if ($this->strength == 'weak')
$pattern = $this->weak_pattern;
elseif ($this->strength == 'strong')
$pattern = $this->strong_pattern;
// extract the attribute value from it's model object
$value=$object->$attribute;
if(!preg_match($pattern, $value))
{
$this->addError($object,$attribute,'your password is too weak!');
}
}
PHP應用上面的辦法我認為就不用解釋了.當然你也可以在 if 的條件中使用常量,我推薦使用.
《PHP應用:PHP YII框架開發小技巧之模型(models)中rules自定義驗證規則》是否對您有啟發,歡迎查看更多與《PHP應用:PHP YII框架開發小技巧之模型(models)中rules自定義驗證規則》相關教程,學精學透。維易PHP學院為您提供精彩教程。
轉載請注明本頁網址:
http://www.snjht.com/jiaocheng/8390.html