yii form Verification Method of JS at Submit Button Before Form Submission

  • 2021-08-03 09:19:33
  • OfStack

Most of the time, it is necessary to judge the rules set by the object in Yii form model, but sometimes it may be necessary to verify it on the client before submission. The setting method here is to set the listener on the submission button. If some contents are empty (for example, the multiple selection button is not selected), an error message will be prompted. The main purpose is to refresh the page without submitting it, and then judge the error after entering the corresponding function of controller. Displays error messages for the rules () validation rule function.

Here, in order to verify whether a radio button is selected, monitor the submitted button onclick, as follows


<Button onclick = "return fun()"/>

To customize fun () function, return, true and false are required


<script>
  function fun(){
    var CheckBox = document.getElementsByName('checkBox[]');// Gets all of the checkBox
    var count=0;
    for(i=0;i < CheckBox.length;i++){
      if(CheckBox[i].checked == true){                
        count++;
      }
    }
    if(count == 0 ){
      var errorMeg = document.getElementById('HomeworkTrConfig_flag_em_');
      errorMeg.style.display = "";
      errorMeg.innerHTML=" Please select at least 1 Items ";      
      return false;
    }else{
      return true;
    }
  }
</script>

Supplement: In Yii form verification, verify before submission, do not pass and do not submit

I used to remember that there is such a writing style, that is, when the contents in the form do not conform to the verification rules, it will not be allowed to submit. I forgot how to write it after a long time, and it was not written in the manual. I checked the information for 1 time and made 1 note:


$form = $this->beginWidget('CActiveForm',array(
    'id' => 'add_host',
    'enableAjaxValidation' => false,
    'enableClientValidation' => true,
    'clientOptions' => array(
        'validateOnSubmit' => true // Verify at this location 
      ),
    'focus' => array($model,'ip')
  ));
?>

Related articles: