How to validate and check if a field contains only letters and whitespace in HTML form with PHP

1 Answer

0 votes
<!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>

 



answered Nov 22, 2015 by avibootz
edited Nov 23, 2015 by avibootz

Related questions

1 answer 305 views
2 answers 306 views
306 views asked Nov 19, 2018 by avibootz
1 answer 264 views
1 answer 217 views
...