2016-04-28 111 views
0

我陷入了一個php的問題。我只想在模型中爲兩個字段添加驗證規則,只要它們顯示在前端。基本上他們是隱藏的。在選擇框的變化時顯示出來,如果它們可見,我希望它們是必需的。 讓我告訴你我的代碼動態在cakePHP 2中添加驗證規則。*

<?php 
    echo $this->JqueryValidation->input('website',array(
      'type' => 'text', 
      'label' => 'Website', 
      'div' => true, 
      'class' => 'form-control', 
      'id' => 'InputWebsite', 
      'placeholder' => 'Enter your website' 
     )); 
?> 
<?php 
    echo $this->JqueryValidation->input('phone',array(
      'type' => 'text', 
      'label' => 'Phone', 
      'div' => true, 
      'class' => 'form-control', 
      'id' => 'InputPhone', 
      'placeholder' => 'Enter your contact Number' 
     )); 
?> 

<script> 
 
    $(document).ready(function() { 
 
    $('#InputPhone').parent('div').hide(); 
 
    $('#InputWebsite').parent('div').hide(); 
 

 

 
    $('#purpose').on('change', function(e) { 
 
     var optionVal = $(this).val(); 
 
     if (optionVal == 'Schedule a call') { 
 
     $('#InputPhone').parent('div').show(); 
 
     $('#InputWebsite').parent('div').show(); 
 
     $("#InputMessage").hide(); 
 
     $("#InputMessage").val(''); 
 
     $(".textarea").hide(); 
 
     } else { 
 
     $('#InputPhone').parent('div').hide(); 
 
     $('#InputPhone').val(''); 
 
     $('#InputWebsite').parent('div').hide(); 
 
     $('#InputWebsite').val(''); 
 
     $("#InputMessage").show(); 
 
     $(".textarea").show(); 
 
     } 
 
    }); 
 
    }); 
 
</script>

是否有可能呢?

回答

0

beforeValidate函數裏面Model中,檢查選擇框值是否是需要驗證其他字段的值。那麼如果是這樣,您需要將驗證規則添加到您的$validate陣列中(使用$this->validate += array(...new rule...);)。