I am trying to create an online entry form for fencing competitions, and am now working on the form validation. The validation is done on the same page, and outputs error messages to the same page, however the problem I have is with checkboxes - when a checkbox is selected, if another error occurs on the page, when the page is re-displayed the checkbox is no longer checked. Any help???
The code is:
<html>
<body>
<h3>PHP Entry Form Example</h3>
<?
// only validate form when form is submitted
if(isset($submit_button)){
$error_msg='';
if(trim($first_name_input)=='' ) {
$error_msg.="Please enter your first name.<br>";
}
if(trim($last_name_input)=='' ) {
$error_msg.="Please enter your surname.<br>";
}
if (($sabre_input=='') && ($foil_input=='') && ($epee_input=='')) {
$error_msg.="Please select at least one weapon.<br>";
}
if(trim($password_input)=='' || strlen(trim($password_input)) < 4) {
$error_msg.="Please enter a password at least 4 characters long<br>";
}
if(trim($email_input)=='') {
$error_msg.="Please enter an email<br>";
} else {
// check if email is a valid address in this format username@domain.com
if(!ereg("0-9a-z@0-9a-z\.[a-z]", $email_input)) $error_msg.="Please enter a valid email address<br>";
}
// display error message if any, if not, proceed to other processing
if($error_msg==''){
// other process here
} else {
echo "<font color=red>$error_msg</font>";
}
}
?>
<form method="POST" action="testvalidation.php">
<table border="1" cellpadding="7" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="100%" id="AutoNumber1">
<tr>
<td width="16%" align="right">First Name</td>
<td width="84%">
<input type="text" name="first_name_input" size="20" value="<? echo $first_name_input; ?>"></td>
</tr>
<tr>
<td width="16%" align="right">Last Name</td>
<td width="84%">
<input type="text" name="last_name_input" size="20" value="<? echo $last_name_input; ?>"></td>
</tr>
<tr>
<td width="16%" align="right">Weapons Entered</td>
<td width="84%"><input name="sabre_input" type="checkbox" value="sabre">
Sabre
<input name="foil_input" type="checkbox" value="foil">
Foil
<input name="epee_input" type="checkbox" value="epee">
Epee</td>
</tr>
<tr>
<td width="16%" align="right">Password</td>
<td width="84%">
<input type="password" name="password_input" size="20" value="<? echo $password_input; ?>">
(must be at least 4 characters)</td>
</tr>
<tr>
<td width="16%" align="right">Email</td>
<td width="84%">
<input type="text" name="email_input" size="20" value="<? echo $email_input; ?>"></td>
</tr>
<tr>
<td width="16%" align="right"> </td>
<td width="84%">
<input type="submit" value=" Register " name="submit_button"></td>
</tr>
</table>
</form>
</body>
</html>