Jump to content


This topic is now archived and is closed to further replies.

steve m

Form Validation

Recommended Posts

Hi there,

I've been trying to come up with a way to validate a form. I came up with this below, but I'm sure there is a more efficient way to do this. I am just writing IF statements and if the statement is true I will assign a variable to a background color in the input field. Is there a more efficient way to do this? Or am I going about this the wrong way?

//$disply_button is the submit button
$bgcolor = "";
if ($model_number == ""){
$bgcolor1 = "background-color: red;";
if ($serial_number == ""){
$bgcolor2 = "background-color: red;";
if ($misc == ""){
$bgcolor3 = "background-color: red;";


Below is the HTML code from closerma3.php. Where the variables will be displayed

<td height="28" width="205">Model:
<input style="<?php echo $bgcolor1; ?>" type="text" name="model_number"onchange="convertField()"
size="20" tabindex="4" value="<?php echo $model_number; ?>">
<td height="28" width="212"><b>Serial:</b>
<input style="<?php echo $bgcolor2; ?>" type="text" name="serial_number" onchange="convertField()"
size="20" tabindex="5" value="<?php echo $serial_number; ?>">
<td height="28" width="198">Misc:
<input style="<?php echo $bgcolor3; ?>" type="text" name="misc" onchange="convertField()"
size="15" tabindex="6" value="<?php echo $misc; ?>">

Share this post

Link to post
Share on other sites
I use a select statement to check the fields and store error messages and/or css color changes in arrays. Also, make sure you don't depend on register_globals being set. In the following code, I'm assuming that your form is using method "POST".
$errs = array();
      foreach($_POST as $k => $v)
           switch($k) {
                  case 'model_number':
                  case 'serial_number':
                  case 'misc':
                          if (trim($v) == '') $errs[$k] = 'style="background-color:red"';

And also change your included file:
$rows = array('model_number' => array('w' => 205, 's'=>20),
                     'serial_number' =>   array('w' => 212, 's'=>20),
                     'misc' => array('w' => 198, 's' => 15));
$tab_index = 4;
$tmp = array();
foreach ($rows as $k => $ary) {
    $x = explode('_',$k);
    $tmp[] = '<td height="28" width="' . $ary['w'] . '">' . ucwords($x[0]) . ': ';
    $style = (isset($errs[$k]))?$errs[$k]:'';
    $tmp[] = '<input ' . $style . ' type="text" name="' . $k . '" onchange="convertField()" size="' . $ary['s'] . '" tabindex="' . $tab_index++ . '" value="' . trim(htmlentities($_POST[$k])) . '">';
echo "<tr>\n" . implode("</td>\n", $tmp) . "</td>\n</tr>\n";


Share this post

Link to post
Share on other sites


Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.