<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$usernameErr = $emailErr = $infoErr = "";
$username = $email = $info = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["username"])) {
$usernameErr = "Name is required";
} else {
$username = test_input($_POST["username"]);
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
if (empty($_POST["info"])) {
$infoErr = "";
} else {
$info = test_input($_POST["info"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2> Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="username">
<span class="error">* <?php echo $usernameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
info: <input type="text" name="info">
<span class="error"><?php echo $infoErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Output Print:</h2>";
echo $username;
echo "<br>";
echo $email;
echo "<br>";
echo $info;
echo "<br>";
?>
</body>
</html>
Output Print
Required fields highlighted
No comments:
Post a Comment