简体   繁体   中英

Yii client-side validation and jQuery Form plugin integration

I'm using Yii framework in one of my projects and I would like to use the jQuery Form plugin together with Yii client-side built-in validation.

I can't get them work together. If I setup jQuery form plugin with this simple js code:

$('#myform-id').ajaxForm();

the client-side validation is performed but it doesn't stop the form submission even if the validation fails. I suppose that this is related to the fact that both Yii client-side validation library and jQuery form plugin bind the same "submit" event on the form.

FYI, I double checked that there no js errors with FireBug and Chrome console.

I wonder if someone experienced the same issue and solved that someway.

I solved this way:

Yii Active Form init code:

<?php $form = $this->beginWidget('CActiveForm', array(
    'id'=>'user-form',
    'enableClientValidation'=>true,
    'clientOptions' => array(
         'validateOnSubmit'=>true,
         'validateOnChange'=>false,
         'afterValidate'=>'js:submiAjaxForm'
     )
)); ?>

And in the same page I've added this js code to submit the form via jquery form plugin:

function submitAjaxForm(form, data, hasError)
{
   if(!hasError)
   {
       $('#user-form').ajaxSubmit(
       {
           // ajax options here
       });
   }
}

On the client-side you can

<?php echo CHtml::activeTextField($model, 'text', array(
                                                            'placeholder'=>$model->getAttributeLabel('text'),
                                                            'class'=>'form-control'
<script>                                                    )); ?>
function Validate(field){
            var _this = field;
            var errorDiv = _this.parent().find('.errors');
            var attr = [];
            _this.each(function(){
                var match = $(this).attr('name').match(/\[(.*?)\]/);
                attr.push(match[1]);
            })

            jQuery.ajax({
                type: 'POST',
                url: 'url/',
                data: 'ajax=keyup&'+_this.serialize()+'&attr='+attr,
                cache: false,
                processData: false,        
                success: function(data){
                    data=JSON.parse(data);
                    if(data.success){
                        _this.addClass('green');
                        errorDiv.html('');

                    }else{
                        _this.addClass('red');
                        errorDiv.html(data[attr][0]);
                    }
                }
            });
        }
        var delay = (function(){ 
            var Timer = 0;
            return function(callback, ms){
                clearTimeout (Timer);
                Timer = setTimeout(callback, ms);
            };
        })(); //if you want to delay

        $('#traveler_info input').keyup(function(){
            var _this = $(this);
            timeout = setTimeout(function(){
                Validate(_this,'Travelers')
            },1000)

        });

` In the SiteController

public function actionAjaxvalidation($type = null)
{   

    $model = new Travelers;

    if( isset($_POST['Travelers'], $_POST['attr']) ) 
    {
        /*
        * @params Model->value $attr 
        *
        */
        $attr = $_POST['attr'];

        $model->$attr = $_POST['Travelers'][$attr];

        if( $model->validate(array($attr)) )
        {   

            echo json_encode(['success'=>true]);

        }
        else
        {
            echo json_encode( $model->errors );
        }

        Yii::app()->end();
    }
}

Try to stop propagation in your submit event:

$('#your-form').submit(function(e){
      e.stopPropagation();
      ... some other code ...
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM