PHP form validation example

Form Validation is a necessary process before the data entered in the form is submitted to the database.

.error {color: #FF0000;}
// define variables and set to empty values
$nameErr = $emailError = $mobileError ="";
$name = $email = $mobile = "";
if (empty($_POST["name"])) {
$nameErr = "Name is required";
else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
if (empty($_POST["name"])) {
$mobileError = "Name is required";
} else {
$mobile = test_input($_POST["mobile"]);
// check if name only contains letters and whitespace
if (!preg_match('/^[0-9]{10}+$/', $mobile)) {
$mobileError = "10 digit Number";
if (empty($_POST["email"])) {
$emailError = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "Invalid email format";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
Mobile: <input type="text" name="mobile" value="<?php echo $mobile;?>">
<span class="error">* <?php echo $mobileError;?></span>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailError;?></span>
<input type="submit" name="submit" value="Submit">

Praveen Kumar

I am a fullstack web developer with a passion for SEO, creating stunning websites, and organic marketing. I am a perfectionist.

Post navigation