Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Form Validation Error Message

$
0
0
Hi guys!

I've been doing some tests with form validation. I have 3 textboxes, all of which need to have data. Whenver the user clicks submit, the form validates on the same page. If no problem was found, it would continue on to insert.php. However, if one or more textbox is left blank, the blank textbox would display a message like "Please enter a first name". It works out fine. The trouble is, those with text lose their text. I'm not sure if you can imagine what I mean, but anyway, here's the code:

<?php
	session_start();
	
	$fname_errormsg = '';
	$mname_errormsg = '';
	$lname_errormsg = '';
	
	if (isset($_POST['submit'])) {
		if (!empty($_POST['fname'])){
			$_SESSION['fname'] = $_POST['fname'];
			if (!empty($_POST['mname'])) {
				$_SESSION['mname'] = $_POST['mname'];
				if (!empty($_POST['lname'])) {
					$_SESSION['lname'] = $_POST['lname'];
					header('location: insert.php');
				} else {
					$lname_errormsg = 'Enter a last name';
				}
			} else {
				$mname_errormsg = 'Enter a middle name';
			}
		} else {
			$fname_errormsg = 'Enter a first name';
		}
	}
?>
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<title>Database Operations</title>
	</head>
	<body>
		<form action="<?php echo htmlentities($_SERVER['PHP_SELF']);?>" method="POST" />
			<table>
				<tbody>
					<tr>
						<td>First Name:</td>
						<td><input type="text" name="fname" value="<?php echo $fname_errormsg; ?>" maxlength="20" /></td>
					</tr>
					<tr>
						<td>Middle Name:</td>
						<td><input type="text" name="mname" value="<?php echo $mname_errormsg; ?>" maxlength="20" /></td>
					</tr>
					<tr>
						<td>Last Name:</td>
						<td><input type="text" name="lname" value="<?php echo $lname_errormsg; ?>" maxlength="20" /></td>
					</tr>
				</tbody>
				<tfoot>
					<tr>
						<td colspan="2"><input type="submit" value="SUBMIT" name="submit" /></td>
					</tr>
				</tfoot>
			</table>
		</form>
	</body>
</html>



Oh, and I'm not quite sure if I've done things neatly. Any suggestion would be highly appreciated. :)/>

Cheers!

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>