yii 使用cactiveform 创建表单时候遇到的一些验证有关问题和使用ajax_form时重置验证规则的解决方法

yii 使用cactiveform 创建表单时候遇到的一些验证问题和使用ajax_form时重置验证规则的解决办法
yii  cactiveform 在添加验证信息的时候, 有时候稍有不慎,可能导致客户端验证不起作用,尤其是像我这种初学者来说,更是无解了, 好在今天有点时间, 一路追查这个问题,最后从js 端一直追到了php中, 终于找到了罪魁祸首,原来还是我们自己,哈哈  接下来就简单分享一下:

首先让我们来看看所有的客户端js验证是怎么添加上去的:
在CActiveForm.php :383行 中有这么一句话:
$options=CJavaScript::encode($options);
		$cs->registerCoreScript('yiiactiveform');
		$id=$this->id;
		$cs->registerScript(__CLASS__.'#'.$id,"jQuery('#$id').yiiactiveform($options);");
这就是根据模型中的规则来添加js验证

同样在492行有这么一段话:(这就是解决client不验证的关键)
if($model instanceof CActiveRecord && !$model->isNewRecord)
   $option['status']=1;
这段代码的意思就是 model必须继承CActiveRecord,但是追重要的是isNewRecord (我就是通过这个status从js追到php的), 然后在继续,到这里瞬间明白了,去看同事的代码,得出以下
Object::model();  isNewRecord  =  false
new Object();       isNewRecord  =  true
话说到这里,为什么我就认定了这个status呢, 当然不是我凭空想的,我是在jquery.yiicactiveform.js中一步一步追查到的,如果你有兴趣一可以看看, 最后在这个js最后发现了他的文件说明,也明显的说明了这一点:就因为使用了Object::model(); 这样这个对象就不是一个新记录了,status就被设置1了,设置为了1在验证中就代表validated了,所以自然就死活都不验证了!
/**
		 * list of attributes to be validated. Each array element is of the following structure:
		 * {
		 *     id: 'ModelClass_attribute', // the unique attribute ID
		 *     model: 'ModelClass', // the model class name
		 *     name: 'name', // attribute name
		 *     inputID: 'input-tag-id',
		 *     errorID: 'error-tag-id',
		 *     value: undefined,
		 *     status: 0,  // 0: empty, not entered before,  1: validated, 2: pending validation, 3: validating
		 *     validationDelay: 200,
		 *     validateOnChange: true,
		 *     validateOnType: false,
		 *     hideErrorMessage: false,
		 *     inputContainer: undefined,
		 *     errorCssClass: 'error',
		 *     successCssClass: 'success',
		 *     validatingCssClass: 'validating',
		 *     enableAjaxValidation: true,
		 *     enableClientValidation: true,
		 *     clientValidation: undefined, // function (value, messages, attribute) | client-side validation
		 *     beforeValidateAttribute: undefined, // function (form, attribute) | boolean
		 *     afterValidateAttribute: undefined,  // function (form, attribute, data, hasError)
		 * }
		 */

第二个问题:

     想必大家也可能有这种需求, 就是一个提交信息的form表单, 比如购物网站的订单页面,这个页面里会有好些信息需要我们填写
     为了说明我的问题,就拿两个信息来举这个例子, 首先最前面会有一个添加收货地址,然后下面会有一些发票信息填写,然后最下面会有一个提交按钮, 当所有的信息都填写完成后,最后统一提交, 那么问题来了,添加收货地址这里肯定会是一个异步form提交,(当然不使用form也可以,但是咱们使用yii吗,就利用他的优势吧), 说到这里这个地址的提交可以使用yii form ajax ,详细不说上代码

<?php
$form = $this->beginWidget('CActiveForm', array(
    'id' => 'addressForm',
    'enableClientValidation' => true, //是否启用客户端验证
    'clientOptions' => array(
        'validateOnSubmit' => true, //提交时验证
        'afterValidate' => 'js:function(form,data,hasError){
            if(!hasError){
                $.ajax({
                    "type":"POST",
                    "url":url,
                    "data":$("#addressForm").serialize(),
                    "success":function(data){
                        var res = eval("("+data+")");
                        if("success"==res.code){
                            if(res.addressId>0){
                                $("#addressId").val(res.addressId);
                            }
                            $("#address_info").prepend(res.html);
                            clearAddr();
                        }else{
                            clearAddr();
                        }
                        },
                    });
                }
            }'
    ),
));
?>
为了更直接在上一张图片
yii 使用cactiveform 创建表单时候遇到的一些验证有关问题和使用ajax_form时重置验证规则的解决方法

想必看到这里大家都明白了吧!

当然刚一进来这个表单肯定是隐藏的,需要点击添加新收货地址才显示出来, 
接下来一个一个分析, 当我添加到一半的时候我不想添了,那么我肯定要点击取消按钮, 这样那些错误信息需要隐藏, 为了使客户端验证在下次点开的时候还能继续使用,我们必须也要初始化yiicactiveform的验证环境,这里由于之前不知道怎么初始化,所以当点击取消后,当再次添加的时候不是验证不能使用就是出现别的问题, 那么还是看jquery.yiicactiveform.js  :177 行
$form.bind('reset', function () {
				/*
				 * because we bind directly to a form reset event, not to a reset button (that could or could not exist),
				 * when this function is executed form elements values have not been reset yet,
				 * because of that we use the setTimeout
				 */
				setTimeout(function () {
					$.each(settings.attributes, function () {
						this.status = 0;
						var $error = $form.find('#' + this.errorID),
							$container = $.fn.yiiactiveform.getInputContainer(this, $form);

						$container.removeClass(
							this.validatingCssClass + ' ' +
							this.errorCssClass + ' ' +
							this.successCssClass
						);

						$error.html('').hide();

						/*
						 * without the setTimeout() we would get here the current entered value before the reset instead of the reseted value
						 */
						this.value = getAFValue($form.find('#' + this.inputID));
					});
					/*
					 * If the form is submited (non ajax) with errors, labels and input gets the class 'error'
					 */
					$form.find('label, :input').each(function () {
						$(this).removeClass(settings.errorCss);
					});
					$('#' + settings.summaryID).hide().find('ul').html('');
					//.. set to initial focus on reset
					if (settings.focus !== undefined && !window.location.hash) {
						$form.find(settings.focus).focus();
					}
				}, 1);
			});
 原来yii 已经给我们实现了, 它已经绑定好reset事件了, 所以 我们只需要恰当的执行
document.getElementById("addressForm").reset();

所有的工作yii 就都给我们处理了!

好了就分享到这里,列兵菜鸟一个如果有什么问题欢迎各位积极提出, 一起进步.