PHP YII架構開發小技巧之模型(models)中rules自訂驗證規則,yiirules_PHP教程

來源:互聯網
上載者:User

PHP YII架構開發小技巧之模型(models)中rules自訂驗證規則,yiirules


YII的models中的rules部分是一些表單的驗證規則,對於表單驗證十分有用,在相應的視圖(views)裡面添加了表單,在表單被提交之前程式都會自動先來這裡面的規則裡驗證,只有通過對其有效限制規則後才能被提交,可以很有效地保證表單安全和資訊的有效性。還是給大傢具體說明一下:

以下是視圖(views)部分的簡單代碼:

<?php $form=$this->beginWidget('CActiveForm', array(   'id'=>'tag-form',   'enableAjaxValidation'=>false, )); ?>        <?php echo $form->labelEx($model,'tagname'); ?>     <?php echo $form->textField($model,'tagname',array('size'=>20,'maxlength'=>32)); ?>           <?php echo $form->labelEx($model,'tagtype'); ?>     <?php echo $form->radioButtonList($model,'tagtype'array(1=>"普通TAG",2=>"系統預設TAG"),array('separator'=>'','labelOptions'=>array('class'=>'tagtypelabel'))); ?>      <?php echo $form->errorSummary($model); ?>        <?php echo CHtml::submitButton($model->isNewRecord ? '添加' : '修改'); ?>    <?php $this->endWidget(); ?> 

模型(models)中rules部分的簡單代碼:

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'),   ); } 

系統預設有這些驗證規則:

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 的別名, 確保了特性匹配一個Regex.
numerical : CNumberValidator 的別名, 確保了特性是一個有效數字.
required : CRequiredValidator 的別名, 確保了特性不為空白.
type : CTypeValidator 的別名, 確保了特性為指定的資料類型.
unique : CUniqueValidator 的別名, 確保了特性在資料表欄位中是唯一的.
url : CUrlValidator 的別名, 確保了特性是一個有效路徑.

基本上還是比較全面的,一般的都夠用了,但是還是有時候有的驗證需要自訂。就以上面的代碼為例,我們在添加TAG時需要檢查系統之前是否已經存在這個TAG,如果存在則不讓使用者添加。這個就需要在添加之前去查詢資料庫,看該TAG是否已經存在,這裡我們就需要自定一個驗證規則了。

關鍵有一下兩個步驟:

1、在rules中 添加代碼:array('tagname', 'checktagname', 'on'=>'create,update'),//插入TAG時檢查是否已經存在該tag

註:我在其中用了 'on'=>'create,update',所以這個驗證規則之對create,update情境生效

2、在該模型(models)中添加驗證函式:

public function checktagname($attribute,$params){   $oldtag = Tag::model()->findByAttributes(array('tagname'=>$this->tagname));   if($oldtag->tagid > 0){     $this->addError($attribute, '該TAG已經存在!');   } } 

其中需要說明的是:

(1)該驗證函式的參數必須是($attribute,$params),不能缺少其中任何一個;

(2)$this->addError($attribute, '該TAG已經存在!');這個是你想要在視圖中輸出的錯誤提示資訊。

就是這麼簡單,有了這個方法,表單驗證的各種想要的規則就都可以自訂了。

下面給大家介紹Yii自訂驗證規則

最簡單的定義驗證規則的方法是在使用它的模型(model)內部定義。

比方說,你要檢查使用者的密碼是否足夠安全.

通常情況下你會使用 CRegularExpression 方法驗證,但為了本指南,我們假設不存在此驗證方法.

首先在模型(model)中添加兩個常量

const WEAK = 0;
const STRONG = 1;然後在模型(model)的 rules 方法中設定:

/** * @return array validation rules for model attributes. */public function rules(){  return array(    array('password', 'passwordStrength', 'strength'=>self::STRONG),  );}

確保你寫的規則不是一個已經存在的規則,否則將會報錯.

現在要做的是在模型(model)中建立一個名稱為上面填寫的規則的方法(即 passwordStrength)。

/** * 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!');}

剛才建立的方法需要兩個參數:* $attribute 需要驗證的屬性* $params 在規則中自訂的參數

在模型的 rules 方法中我們驗證的是 password 屬性,所以在驗證規則中需要驗證的屬性值應該是 password.

在 rules 方法中我們還設定了自訂的參數 strength,它的值將會放到 $params 數組中.

你會發現在方法中我們使用了 CModel::addError().

添加錯誤接受兩個參數:第一個參數是在表單中顯示錯誤的屬性名稱,第二個參數時顯示的錯誤資訊 。

完整的方法:繼承 CValidator 類

如果你想把規則使用在多個模型(model)中,最好的方法時繼承 CValidator 類。

繼承這個類你可以使用像 CActiveForm::$enableClientValidation (Yii 1.1.7 版本後可用) 類似的其他功能。

建立類檔案

首先要做的是建立類檔案.最好的方法時類的檔案名稱和類名相同,可以使用 yii 的消極式載入(lazy loading)功能。

讓我們在應用(application)的擴充(extensiions)目錄(在 protected 檔案夾下)下建立一個檔案夾.

將目錄命名為: MyValidators

然後建立檔案: passwordStrength.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,}$/';...}

在類中建立屬性,此屬性為在驗證規則中使用的參數.

CValidator 會自動根據參數來填充這些屬性.

我們也建立了兩個其他的屬性,它們為 preg_match 函數使用的Regex.

現在我們應該重寫父類的抽象方法(abstract method) validateAttribute

/** * 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!');  }}

上面的方法我認為就不用解釋了.當然你也可以在 if 的條件中使用常量,我推薦使用.

http://www.bkjia.com/PHPjc/1072188.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1072188.htmlTechArticlePHP YII架構開發小技巧之模型(models)中rules自訂驗證規則,yiirules YII的models中的rules部分是一些表單的驗證規則,對於表單驗證十分有用,在...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.