3

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?

2 Answers 2

6
<?php echo $form->textField($model,'name', array('class'=>'input' . ( $model->getError('name')  ? ' error' : ''))); ?>
Sign up to request clarification or add additional context in comments.

1 Comment

This 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 . . .
3

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"); 
              }'
          ),
        )); ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.