jQuery: input array object validation

Use of input array objects in ajax based forms where we want to give users open ended options to add unlimited number of items and then process them on form submission is very common now a days. As the input elements all have the same name and assuming no class or id attribute is available, validation can be a big pain in the back side.

The following code excerpt shows how to validate in such a scenario -

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content=
"HTML Tidy for Windows (vers 14 February 2006), see www.w3.org" />
<meta http-equiv="content-type" content=
"text/html; charset=us-ascii" />
<title>Hello World</title>

<script type="text/javascript" src=
"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript">
//<![CDATA[
      function checkname(fieldname){
      var field = document.getElementsByName(fieldname+"[]");

      var status = 1;
      for(i=0;i<field.length;i++){
        if(status > 0){
          if(field[i].value == ''){
            status = 0;
          }
        }
      }
      
      if(status == 0){alert('The field can not be empty!');}
    }
//]]>
</script>
</head>
<body>
<form method="post" action="" name="form" id="form">
 <input type="text" name="faisal[]" value="" />
 <input type="text" name="faisal[]" value="" />
 <input type="text" name="faisal[]" value="" />
 <input type="text" name="faisal[]" value="" />
 <select name="ahmed[]">
  <option value="">None</option>
  <option value="1">1</option>
 </select>
 <input type="submit" value="test" onclick="checkname('ahmed');" />
</form>
</body>
</html>

Comments and queries are welcomed :)

thephpx

[ad code=1 align=center]

Share

About thephpx

I am a freelance web application developer. I work with PHP5 and MySQL. Most of my projects are done using the codeIgniter framework.I am also working towards moving onto the Zend Framework. I follow agile development methodology and manage my projects throuh SCRUM based approach. Apart from being a developer I am also the CEO of a small web identity and application development firm located in dhaka, bangladesh. The firm known as 'implode impressions' also follows agile development techniques and works under the SCRUM based approach.

One response to “jQuery: input array object validation

  1. Hey, I have similar form..
    I need help them sending via jquery-ajax.

    can you help

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>