0

i'm using Jquery validate plugin to validate a form.

I fill my form dynamically using php.. for example:

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

I have to validate this form.. so for static field there is no problem:

$('#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!",
   }
});

but how can i loop through dynamic field to validate them?

Thanks to everybody!

1 Answer 1

2

you can use:

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

and put class='required' on every input.So your code will be:

<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>
Sign up to request clarification or add additional context in comments.

3 Comments

If the message is not specified, by default the message is: "This field is required.",
If you want to change the error message for all the required fields you can do this: $.extend($.validator.messages, { required: "Required custom message" }); Or do you want to make a custom message for each input field?
i prefer custom message for all fields

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.