Jump to content


Photo

validating a form


  • Please log in to reply
3 replies to this topic

#1 jdubwelch

jdubwelch
  • Members
  • PipPipPip
  • Advanced Member
  • 85 posts

Posted 31 March 2006 - 03:20 AM

I have 16 input boxes where users need to rank items 1 through 16. I need to make some sort of validation system so they can't enter in the same number twice.

How would i got through and check to see if there's no doubles of numbers besides doing a bunch of coding for.

For example, say the input boxes are A, B, ..., O, P. I don't want to be like:

if ( A == B || A== C || A== D ... || A== O ) {
// not valid;
} else {
//is valid;
}

if i did it that way, that would be a heck of a lot of coding and quite a headache. I was thinking possibly putting each value into an array and then checking A through the rest of the array, but not really sure how code that or what it'd look like.

any suggestions?

#2 gavinandresen

gavinandresen
  • Members
  • PipPip
  • Member
  • 10 posts

Posted 02 April 2006 - 01:27 AM

Here's how I did it; you can try it out at:
[a href=\"http://www.skypaint.com/gavin/code/rankIt.php\" target=\"_blank\"]http://www.skypaint.com/gavin/code/rankIt.php[/a]
... and download the code from there.


<?php
ob_start();
?>
<html>
<head>
<title>fillInForm: lots of select boxes example</title>
<style>
.error { color: red; }
</style>
</head>
<body>
<p>Sixteen, sixteen-valued selects.  Validation is making sure there
are no duplicates...
</p>
<h1>Rank Them!</h1>
<ul class="error"><li>PLACEHOLDER FOR FORM ERRORS</li></ul>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST">
<table border="0">
<?php for ($i = 1; $i <= 16; $i++) {
  $name = "rank_$i";
?>
<tr>
 <td><label for="<?php echo $name; ?>">Item <?php echo $name; ?>:</label></td>
 <td><select name="<?php echo $name; ?>" id="<?php echo $name; ?>">
<?php
  for ($j = 1; $j <= 16; $j++) { echo "<option value=\"$j\">$j</option>"; }
?>
  </select>
 </td>
</tr>
<?php
} // Phew, end of 16 select boxes.
?>
<tr><td> </td>
 <td><input type="submit" name="submit" value="Rank'Em"></td>
</tr>
</table>
</form>
<p><hr/><a href="fillInFormValues.zip">Download PHP code</a></p>
</body>
</html>
<?php
$html = ob_get_contents();
ob_end_clean();

require_once("fillInFormValues.php");
require_once("validateForm.php");

$request = (get_magic_quotes_gpc() ? array_map('stripslashes', $_REQUEST) : $_REQUEST);

for ($i = 1; $i <= 16; $i++) {
  $name = "rank_$i";
  $validationData[$name] = array('isRequired', 'type' => 'number');
}
if (isset($request['submit'])) {
  $formErrors = validateForm($request, $validationData);

  $checkDuplicates = array();
  for ($i = 1; $i <= 16; $i++) {
    $name = "rank_$i";
    $rank = $request[$name];
    if (isset($checkDuplicates[$rank])) {
      $formErrors[$name] = "You ranked two or more items as number $rank";
    }
    else if (!empty($rank)) {
      $checkDuplicates[$rank] = $name;
    }
  }

  if (count($formErrors) == 0) {
    // Normally there would be code here to process the form
    // and redirect to a thank you page...
    // ... but for this example, we just always re-display the form.
    $info = "No errors; got these values:".
      nl2br(htmlspecialchars(print_r($request, 1)));
    $html = preg_replace('/<body>/', "<body><p>$info</p>", $html);
  }
}
else {
  $formErrors = array();
}

echo fillInFormValues($html, $request, $formErrors);

?>


#3 Zane

Zane
  • Administrators
  • Advanced Member
  • 4,134 posts

Posted 02 April 2006 - 03:28 AM

on your input boxes..the HTML part
change the name of each box to something like whatever[]...note the brackets
the when the form is sent you'll have a 0 to 15 list of all the input in an array called whatever

A<input name='stuff[]' type='text'>
B<input name='stuff[]' type='text'>
C<input name='stuff[]' type='text'>
D<input name='stuff[]' type='text'>
//$stuff[2] would be the C one

anyway...once you do that...do a foreach loop with it
to make sure each one is unique
and if it is just continue
if not.....stop everything I guess and throw your error

say
foreach($stuff as $val) [
 if(in_array($val, $stuff))
   die("ERROR");
}

btn_donate_SM.gif Want to thank me? Contribute to my PayPal piggy-bank
 

172938.png

#4 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 02 April 2006 - 04:14 AM

Here's my take on the problem.

I used radio buttons for inputting the ranking on each item and used the array_unique() function to determine whether 16 unique rankings were entered. About 1/2 of the code is PHP the other 1/2 is CSS styling information to make the form and the errors look "nice" . :-)

<?php
$err_style = array();
$radio_sylye = array();
if (isset($_POST['submit'])) {
    $unique_opts = array_unique($_POST['opt']);
    for ($i=1;$i<17;$i++)
        if (!isset($unique_opts[$i])) {
            $err_style[$i] = ' style="color:red;font-weight:bold;"';
            $radio_style[$i] = ' style="background-color: red';
        }
}
?>
< !DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
    <title>Ranking Test</title>
    <style type="text/css" media="screen">
    .row {
        clear:both;
        display:block;
        height:1.5em;
        width:100%;
    }
    .label {
        display:block;
        float:left;
        width:5em;
    }
    .header {
        float:left;
        display:block;
        height:1.5em;
        width:2em;
        text-decoration:underline;
        font-weight:bold;
    }
    .radiob {
        float:left;
        display:block;
        height:1.5em;
        width:2em;
    }
    .sub {
        clear:both;
        float:left;
        display:block;
        margin-top:0.25em;
    }
    .red {
        color: Red;
    }
    
    .bold {
        font-weight: bold;
    }
    
    hr {
        clear: both;
    }
    </style>
</head>

<body>
<form method="post">
<div class="row"><span class="label"> </span>
<?php
for ($i=1;$i<17;$i++)
    echo '<span class="header">' . $i . '</span>';
echo '</div>'."\n";
for ($row = 1; $row < 17; $row++) {
    echo '<div class="row"><span class="label"';
    if (isset($err_style[$row])) echo $err_style[$row];
    echo '>Item #' . $row . ':</span>';
    for ($opt = 1; $opt < 17; $opt++) {
        echo '<span class="radiob"';
        if (isset($_POST['opt'][$row]) && $_POST['opt'][$row] == $opt && isset($radio_style[$row])) echo $radio_style[$row];
        echo '">';
        echo '<input type="radio" id="opt_' . $row . '_' . $opt . '" name="opt[' . $row . ']" value="' . $opt . '"';
        if (isset($_POST['opt'][$row]) && $_POST['opt'][$row] == $opt) {
            echo ' checked="checked"';
        }
        echo '></span>'; }
    echo "</div>\n";}
?>
<div class="sub"><input type="submit" name="submit" value="Submit Rankings"></div>
</form>
<?php
if (isset($_POST['submit'])) {
    echo '<hr>';
    if (count($_POST['opt']) != 16) echo "<p class='red'>You didn't rank all of the items, try again</p>\n";
    else {
        $unique_opts = array_unique($_POST['opt']);
        if (count($unique_opts) != 16) {// duplicate ranking found
            $tmp = array();
            for ($i=1;$i<17;$i++){
                if (!isset($unique_opts[$i])) $tmp[] = $i.'<span class="bold">(Rank: ' . $_POST['opt'][$i] . ')</span>';
            }
            echo 'The rankings of the following Items were already used: ' . implode(', ',$tmp) . '<br>';
        }
    }
}
?>
</body>
</html>

You can try it out at [a href=\"http://www.rbnsn.com/phpfreaks/ranking.php\" target=\"_blank\"]http://www.rbnsn.com/phpfreaks/ranking.php[/a]

(Note: remove the space after the "<" on the DOCTYPE line)

Ken




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users