2013-10-29 44 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 
    } 
}