简体   繁体   中英

Yii. How to add css “error” class to input on form submit?

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?

<?php echo $form->textField($model,'name', array('class'=>'input' . ( $model->getError('name')  ? ' error' : ''))); ?>

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

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