2012-08-31 73 views
0

我使用Jquery validate plugin來驗證表單。使用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!", 
    } 
}); 

卻怎麼也我通過動態字段來驗證它們?

感謝大家!

回答

2

你可以使用:

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

,並把class='required'每input.So你的代碼將是:

<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> 
+0

什麼消息? – JackTurky

+0

如果未指定消息,默認情況下消息是:「此字段是必需的。」, –

+0

如果我想更改它? – JackTurky