I found this question and I had the same issue, so I thought I would post my solution.
I needed to disable clientSide validation on specific fields when a checkbox was checked/unchecked using Yii.
Note my solution uses the $form CActiveForm widget.
So the form code:
<?php
$form=$this->beginWidget('CActiveForm', array(
'id'=>'my-form',
'enableAjaxValidation'=>false,
));
?>
<input type="checkbox" name="YourCheckbox" id="Your-Checkbox" value="1" />
<?php
echo $form->labelEx($yourModel,'FirstName');
echo $form->textField($yourModel,'FirstName');
echo $form->error($yourModel,'FirstName');
echo $form->labelEx($yourModel,'LastName');
echo $form->textField($yourModel,'LastName');
echo $form->error($yourModel,'LastName');
?>
Now we display the javascript functions which will disable the validation for each field you specify:
function enableFieldsValidation(form, model, fieldName) {
// Restore validation for model attributes
$.each(form.data('settings').attributes, function (i, attribute) {
if (attribute.model == model && attribute.id == (model + '_' + fieldName))
{
if (attribute.hasOwnProperty('disabledClientValidation')) {
// Restore validation function
attribute.clientValidation = attribute.disabledClientValidation;
delete attribute.disabledClientValidation;
// Restore sucess css class
attribute.successCssClass = attribute.disabledSuccessCssClass;
delete attribute.disabledSuccessCssClass;
}
}
});
}
function disableFieldsValidation(form, model, fieldName) {
$.each(form.data('settings').attributes, function (i, attribute) {
if (attribute.model == model && attribute.id == (model + '_' + fieldName))
{
if (!attribute.hasOwnProperty('disabledClientValidation')) {
// Remove validation function
attribute.disabledClientValidation = attribute.clientValidation;
delete attribute.clientValidation;
// Reset style of elements
$.fn.yiiactiveform.getInputContainer(attribute, form).removeClass(
attribute.validatingCssClass + ' ' +
attribute.errorCssClass + ' ' +
attribute.successCssClass
);
// Reset validation status
attribute.status = 2;
// Hide error messages
form.find('#' + attribute.errorID).toggle(false);
// Dont make it 'green' when validation is called
attribute.disabledSuccessCssClass = attribute.successCssClass;
attribute.successCssClass = '';
}
}
});
}
Once you have these functions in your JS file you can use jQuery to check if the checkbox has been checked. If it has been checked it will enable validation and if not it will disable it.
$('#YourCheckbox').click(function() {
if ($(this).is(':checked'))
{
enableFieldsValidation($('#my-form'), 'YourModel', 'FirstName');
//enableFieldsValidation($('#my-form'), 'YourModel', 'LastName');
}
else
{
disableFieldsValidation($('#my-form'), 'YourModel', 'FirstName');
//disableFieldsValidation($('#my-form'), 'YourModel', 'LastName');
}
});