我们看到 当我什么都不填就提交的时候 就会出现如下错误
//在验证逻辑中,它判断是否为空,如果为空则调用addError方法把错误信息添加到model的errors属性中,这样在active_form视图中, <?php echo $form->error($model,'username'); ?> 就会输出对应字段的错误信息 <?php echo $form->errorSummary($model); ?> 就会输出所有的错误信息 protected function validateAttribute($object,$attribute) { $value=$object->$attribute; if($this->requiredValue!==null) { if(!$this->strict && $value!=$this->requiredValue || $this->strict && $value!==$this->requiredValue) { $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} must be {value}.', array('{value}'=>$this->requiredValue)); $this->addError($object,$attribute,$message); } } elseif($this->isEmpty($value,$this->trim)) { $message=$this->message!==null?$this->message:Yii::t('yii','{attribute} cannot be blank.'); $this->addError($object,$attribute,$message); } }
<?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'user-active_form-form', // Please note: When you enable ajax validation, make sure the corresponding // controller action is handling ajax validation correctly. // See class documentation of CActiveForm for details on this, // you need to use the performAjaxValidation()-method described there. 'enableAjaxValidation'=>false, 'enableClientValidation'=>true,//加上这行就开启了客户端js验证了 )); ?>当我们再次刷新页面,可以看到,当光标聚焦用户名输入框又移动开之后会出现下图错误
<?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'user-active_form-form', // you need to use the performAjaxValidation()-method described there. 'enableAjaxValidation'=>true,//开启ajax验证 'enableClientValidation'=>false,//为了避免混淆我们把客户端验证先关掉 )); ?>然后在控制器中定义一个ajax验证model的方法performAjaxValidation()
protected function performAjaxValidation($model){ // uncomment the following code to enable ajax-based validation if(isset($_POST['ajax']) && $_POST['ajax']==='user-active_form-form') { echo CActiveForm::validate($model); Yii::app()->end(); } }然后在方法actionActiveform中调用此方法
开启ajax验证后,activeform的配置中有一个clientOptions属性可以用来控制ajax触发的时机
'enableClientValidation'=>false, 'clientOptions'=>array( 'validateOnSubmit'=>true,//开启表单提交onsubmit时验证,如果为false则提交表单时不会去验证 'validateOnChange'=>false,//开启输入值被改变时onchange验证,如果为false,则输入值改变不会去验证 ),
public string error ( CModel $model, string $attribute, array $htmlOptions=array ( ), boolean $enableAjaxValidation=true, boolean $enableClientValidation=true) //比如username 我们想开启ajax验证,不需要客户端验证,可以这样去配置 <?php echo $form->error($model,'username',array(),true,false); ?> //比如city_id,我们只想开启客户端验证,可以这样去配置 <?php echo $form->error($model,'city_id',array(),false,true); ?>