Reputation: 4769
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.
Upvotes: 0
Views: 6518
Reputation: 5358
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();
}
}
Upvotes: 0
Reputation: 4769
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
});
}
}
Upvotes: 5
Reputation: 7377
Try to stop propagation in your submit event:
$('#your-form').submit(function(e){
e.stopPropagation();
... some other code ...
});
Upvotes: 0