2013-10-29 53 views
2

我的前端是Phi Yii。我正在嘗試創建一個自定義驗證規則,檢查數據庫中是否已存在用戶名。自定義驗證規則不適用於CFormModel

我沒有直接訪問數據庫的權限。我必須使用RestClient與數據庫進行通信。我的問題是自定義驗證規則不適用於我的CFormModel。

這裏是我的代碼:

public function rules() 
{ 
    return array(
     array('name', 'length', 'max' => 255), 
     array('nickname','match','pattern'=> '/^([a-zA-Z0-9_-])+$/') 
     array('nickname','alreadyexists'), 
    ); 
} 

public function alreadyexists($attribute, $params) 
{ 
    $result = ProviderUtil::CheckProviderByNickName($this->nickname); 
    if($result==-1) 
    { 
    $this->addError($attribute, 
     'This Provider handler already exists. Please try with a different one.'); 
    } 

這似乎並沒有在所有的工作,我也試過這樣:即使是這樣,它似乎

public function alreadyexists($attribute, $params) 
{ 
    $this->addError($attribute, 
     'This Provider handler already exists. Please try with a different one.'); 

} 

不工作。我在這裏做錯了什麼?

回答

1

您的代碼的問題是它不返回truefalse

這裏是我的規則之一,以幫助您:

<?php 
.... 
    public function rules() 
    { 
     // NOTE: you should only define rules for those attributes that 
     // will receive user inputs. 
     return array(
      array('title, link', 'required'), 
      array('title, link', 'length', 'max' => 45), 
      array('description', 'length', 'max' => 200), 
      array('sections','atleast_three'), 

     ); 
    } 
    public function atleast_three() 
    { 
     if(count($this->sections) < 3) 
     { 
      $this->addError('sections','chose 3 at least.'); 
      return false; 
     } 
     return true; 
    } 

... 

?> 
0

我遇到了同樣的問題,終於得到了解決。希望解決方案對解決您的問題很有用。

爲什麼定製驗證功能不叫的原因是:

  1. 這是一個服務器端,而不是客戶端驗證
  2. 當你點擊「提交」按鈕,控制器功能接管過程首先
  3. 自定義功能不會介入,如果你沒有叫「$模型 - >的validate()」

因此,解決方案其實很簡單:

在控制器功能中添加「$ model-> validate()」。這裏是我的代碼:

「valid.php」:

<?php $form=$this->beginWidget('CActiveForm', array(
    'id'=>'alloc-form', 
    'enableClientValidation'=>true, 
    'clientOptions'=>array('validateOnSubmit'=>true,), 
)); ?> 

<?php echo $form->errorSummary($model); ?> 

<div class="row"> 
    <?php echo $form->labelEx($model,'valid_field'); ?> 
    <?php echo $form->textField($model,'valid_field'); ?> 
    <?php echo $form->error($model,'valid_field'); ?> 
</div> 

<div class="row buttons"> 
    <?php echo CHtml::submitButton('Submit'); ?> 
</div> 

<?php $this->endWidget(); ?> 

「ValidForm.php」:

class ValidForm extends CFormModel 
{ 
    public $valid_field; 

    public function rules() 
    { 
     return array(
      array('valid_field', 'customValidation'), 
     ); 
    } 

    public function customValidation($attribute,$params) 
    { 
     $this->addError($attribute,'bla'); 
    } 
} 

「SiteController.php」

public function actionValid() 
{ 
    $model = new ValidForm; 

    if(isset($_POST['AllocationForm'])) 
    { 
     // "customValidation" function won't be called unless this part is added 
    if($model->validate()) 
     { 
      // do something 
     } 
     // do something 
    } 
}