Sekhu
Sekhu

Reputation: 139

Validating generated input fields

How will I validate the input boxes which are generated in a PHP for loop using jQuery? In my code I am using jquery.min.js library and jquery.validate.min.js and simply calling the validate function.

I am getting error messages for only first row but not for the other rows. any suggesion much appreciated ... thanxx in advance.

<html>
<head>
<TITLE></TITLE>
<script type="text/javascript" src="first/js/jquery.min.js"></script>
<script type="text/javascript" src="first/js/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

         $("#frm").validate({
                    rules:{
                        'name[]':{
                            required:true
                        },
                        'mail[]':{
                            required:true,
                            email:true
                         }
                    },
                    messages:{
            'name[]':{
                required:"Enter name"
            },
             'mail[]':{
                            required:" Enter mail",
                            email:"Enter valid mail"
                        }
                    },

                    submitHandler:function(){
                        form.submit();
                    }
                });
            });
</script>
</head>

<body>
<form name="frm" id="frm" action="exa.php">
<table>
<tr><TH>Name:</TH><TH>Email:</TH></tr>
<?php
for ($i=1;$i<=3;$i++)
{
?>
<tr><TD><input name="name[]" type="text" id="name[]" class="required" minlength="2"/></TD>
<TD><input name="mail[]" type="text" id="mail[]" class="required email" /></TD></tr>
<?php
}
?>

<tr><TD colspan="2" align="center"><input type="submit" name="submit" value="Submit"></TD></tr>

</table>
</form>
</body>
</html>

Upvotes: 1

Views: 719

Answers (2)

mlwacosmos
mlwacosmos

Reputation: 4561

Indeed, it looks like it is not naturally possible.

But you can change the source of jquery.validate.js. There is another stackoverflow post :

https://stackoverflow.com/a/4136430/432513

and especially : http://www.codeboss.in/web-funda/2009/05/27/jquery-validation-for-array-of-input-elements/

Upvotes: 1

draxxxeus
draxxxeus

Reputation: 1523

Most of the modern browsers now are HTML5 compatible and if you think your website will be accessed from HTML5 compatible browsers, I suggest that you use the required attribute for <input> and email type.

Eg:

<input type='text' name='name[]' required />
<input type='email' name='email[]' required />    

These will only work if you write <!DOCTYPE HTML> before <html>.

I guess this would be the cleanest way to validate your input fields

Upvotes: 1

Related Questions