<!DOCTYPE HTML>
<html>
<head>
<style>
.error_message {color: #FF0000;}
</style></head>
<body>
<?php
$err_msg = "";
$user_name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["user_name"]))
{
$err_msg = "User Name is required";
}
else
{
$user_name = clean_input($_POST["user_name"]);
// check if user_name contains only letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $user_name))
{
$err_msg = "Write only letters and white";
}
}
}
function clean_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?><h3>Form Validation With PHP</h3>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
User Name: <input type="text" name="user_name">
<span class="error_message">* <?php echo $err_msg;?></span>
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "user name = " . $user_name;
?>
</body>
</html>