2016-04-28 107 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...);)。