steve m Posted May 2, 2006 Share Posted May 2, 2006 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?<?php//$disply_button is the submit buttonif(isset($disply_button)){ $bgcolor = ""; if ($model_number == ""){ $bgcolor1 = "background-color: red;"; } if ($serial_number == ""){ $bgcolor2 = "background-color: red;"; } if ($misc == ""){ $bgcolor3 = "background-color: red;"; } include("closerma3.php");}?>Below is the HTML code from closerma3.php. Where the variables will be displayed<tr> <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> <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> <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; ?>"> </td></tr> Link to comment https://forums.phpfreaks.com/topic/8910-form-validation/ Share on other sites More sharing options...
kenrbnsn Posted May 2, 2006 Share Posted May 2, 2006 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".[code]<?php$errs = array();if(isset($_POST['disply_button'])){ foreach($_POST as $k => $v) switch($k) { case 'model_number': case 'serial_number': case 'misc': if (trim($v) == '') $errs[$k] = 'style="background-color:red"'; break; }}?>[/code]And also change your included file:[code]<?php$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";?>[/code]Ken Link to comment https://forums.phpfreaks.com/topic/8910-form-validation/#findComment-32733 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.