Yii. How to add css "error" class to input on form submit?
12,212
Solution 1
To have AJAX validation also, you should add something more or less like this:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'contact-form',
'enableClientValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'afterValidate' => 'js:function(form, data, hasError) {
if(hasError) {
for(var i in data) $("#"+i).addClass("error_input");
return false;
}
else {
form.children().removeClass("error_input");
return true;
}
}',
'afterValidateAttribute' => 'js:function(form, attribute, data, hasError) {
if(hasError) $("#"+attribute.id).addClass("error_input");
else $("#"+attribute.id).removeClass("error_input");
}'
),
)); ?>
Solution 2
<?php echo $form->textField($model,'name', array('class'=>'input' . ( $model->getError('name') ? ' error' : ''))); ?>
Author by
Mantas Vaitkūnas
Updated on June 04, 2022Comments
-
Mantas Vaitkūnas almost 2 years
I have Yii form. Some fields are required. When form is submitted i need that CSS class "error" would be added to the text input. My Code:
<?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'contact-form', 'enableClientValidation'=>true, 'clientOptions'=>array( 'validateOnSubmit'=>true, ), )); ?> <ul class="contact_form"> <li class="row"> <?php echo $form->labelEx($model,'name'); ?> <?php echo $form->textField($model,'name', array('class'=>'input')); ?> <?php echo $form->error($model,'name'); ?> </li> ...
Now i just get div with error message:
<div class="errorMessage" id="ContactForm_name_em_" style="">Laukelis „Vardas, pavardė“ negali būti tuščias.</div>
How to add "error" class to input field?
-
ernie over 11 yearsThis answer looks like it should work if you were using a regular form submit, but looks like you're using AJAX submit and client side validation. I don't think there's an easy way to do this, w/o writing your own AJAX function on submit or extending Yii's validation methods . . .