0

我正在使用Jquery 验证插件来验证表单。

我使用 php 动态填写表单。例如:

<form name="my_form" id="my_form">
   <label for="static_field_1">Insert static field 1</label>
   <input type="text" name="static_field_1" id="static_field_1"/>
   <label for="static_field_2">Insert static field 2</label>
   <input type="text" name="static_field_2" id="static_field_2" />

   <?php
      $no_dynamic_field = count($dynamic_fields_array);
      if($no_dynamic_field>0){
         for($i=0;$i<$no_dynamic_field;$i++){
   ?>
         <label for="dynamic_field_<?php echo $i;?>">Insert field <?php echo $dynamic_fields_array[$i];?></label> 
         <input type="text" name="dynamic_field_<?php echo $i;?>" id="dynamic_field_<?php echo $i;?>" />
   <?php
         }
      }
   ?>
</form>

我必须验证这个表格。所以对于静态字段没有问题:

$('#my_form').validate({
   rules: {
      static_field_1:"required",
      static_field_2:"required"
   },
   messages:{
      static_field_1:"Static field 1 required!",
      static_field_2:"Static field 2 required!",
   }
});

但是我怎样才能遍历动态字段来验证它们呢?

谢谢大家!

4

1 回答 1

2

您可以使用:

$(document).ready(function(){
    $('#my_form').validate();
});

class='required'输入每个输入。因此您的代码将是:

<form name="my_form" id="my_form">
   <label for="static_field_1">Insert static field 1</label>
   <input type="text" name="static_field_1" id="static_field_1" class='required'/>
   <label for="static_field_2">Insert static field 2</label>
   <input type="text" name="static_field_2" id="static_field_2" class='required'/>

   <?php if(count($dynamic_fields_array)>0)
      for($i=0;$i<count($dynamic_fields_array);$i++){
   ?>
      <label for="dynamic_field_<?php echo $i;?>">Insert field <?php echo $dynamic_fields_array[$i];?></label> 
      <input type="text" name="dynamic_field_<?php echo $i;?>" id="dynamic_field_<?php echo $i;?>" class='required'/>
   <?php
      }
   ?>
   <?php }?>
</form>
于 2012-08-31T08:32:23.363 回答