<!DOCTYPE HTML>
<html>
<head>
<style>
.error_color {color: #FF0000;}
</style>
</head>
<body><?php
$nameError = $emailError = $genderError = "";
$name = $email = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameError = "Name is required";
} else {
$name = clean_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameError = "Please Enter only letters and white-space";
}
}
if (empty($_POST["email"])) {
$emailError = "Email is required";
} else {
$email = clean_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "Invalid email";
}
}
if (empty($_POST["gender"])) {
$genderError = "Gender is required";
} else {
$gender = clean_input($_POST["gender"]);
}
}
function clean_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?><h2>PHP Form Validation</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error_color">* <?php echo $nameError;?></span>
<br /><br />
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error_color">* <?php echo $emailError;?></span>
<br /><br />
Gender:
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="female") echo "checked";?> value="female">Female
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="male") echo "checked";?> value="male">Male
<input type="radio" name="gender" <?php if (isset($gender) && $gender=="other") echo "checked";?> value="other">Other
<span class="error_color">* <?php echo $genderError;?></span>
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Form Data:</h2>";
echo $name;
echo "<br />";
echo $email;
echo "<br />";
echo $gender;
?>
</body>
</html>
<!--
Form Data:
Fox
fox@email.com
male
-->