Page 1 of 1

verify required fields (dynamic text fields)

Posted: Fri Mar 09, 2012 9:33 am
by cherrydee
here's my code for static text field:

Code: Select all

function displayerror($fieldname, $errormsg)
{
   global $errorcount;
   echo "Error for $fieldname: $errormsg<br />";
   $errorcount++;
}


function validateinput($data, $fieldname)
{
   global $errorcount;
   $totalquiz=($_POST['totalquiz']);

   if(empty($data))
   {
      displayerror($fieldname, "This field is required" . "<br>");
      $errorcount=1;
      $retval="";
   }
   else
   {
      $retval = trim($data);
      $retval = stripslashes($retval);
      if(!is_numeric($totalquiz))
      {
      displayerror($fieldname, "This field should be numeric" . "<br>");
      $errorcount=1;
      }

   }   
      return($retval);
}
$totalquiz=validateinput($_POST['totalquiz'], "Total # of quizzes");
if($errorcount>0)
   echo "please use the back button to re-enter the data" . "<br>";
else
{
echo $totalquiz;
my problem is how can i apply this if my text fields are dynamic?
let's say in my index.html there's a button that ask how many quiz are there. so if i put 2, 2 text fields are generate w/ name property ="quiz"
how can i apply this array looping in the above codes? :|
~~~~~~~~~~~~~~~PS:
here's the folder containing my work. i know its wrong to post download links but i swear i don't have any bad intentions. this is just for a better vision of what i'm trying to do
http://www.mediafire.com/?gbhicntq4kknnhv
index=home
calculation=page for the calculation
handler=process codes

Re: verify required fields (dynamic text fields)

Posted: Sat Mar 10, 2012 7:31 am
by Eric!
When you make your form you have to give the input fields a unique name like "quiz1", "quiz2", etc. then just loop through (foreach $_POST[]) value and check them.

Re: verify required fields (dynamic text fields)

Posted: Thu Mar 15, 2012 9:33 am
by whiterainbow
An easy way to do what Eric mentioned might be using ${var.$i}, or by putting all the quizzes into an array. So for example

Code: Select all

$i=1;
while ($i<=10) {
   ${quiz.$i} = $_POST[quiz.$i]
}
This will give you a set of variables $quiz1, $quiz2 etc. I should note that you could probably do this more quickly (in terms of page loads) with something like jQuery.