This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

Test Form - Required Fields

PHP Form Validation Example With err Messages

PHP Form Validation Example

* required field

Name: *

E-mail: *

Website:

Comment:

Gender: Female Male Other *

Your Input:





<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

// check whether the required fields are filled when the submit button is clicked/pressed
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
  }
  
  if (empty($_POST["email"])) {
    $emailErr = "Email is required";
  } else {
    $email = test_input($_POST["email"]);
  }
    
  if (empty($_POST["website"])) {
    $website = "";
  } else {
    $website = test_input($_POST["website"]);
  }

  if (empty($_POST["comment"])) {
    $comment = "";
  } else {
    $comment = test_input($_POST["comment"]);
  }

  if (empty($_POST["gender"])) {
    $genderErr = "Gender is required";
  } else {
    $gender = test_input($_POST["gender"]);
  }
}

// function to sanitize the provided data
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
?>

// PHP code for the different form elements
form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"
name:
  <span class="error">* <?php echo $nameErr;?></span>
email:
  <span class="error">* <?php echo $emailErr;?></span>
website:
  <span class="error"><?php echo $websiteErr;?></span>
gender:
  <input type="radio" name="gender" value="female">Female
  <input type="radio" name="gender" value="male">Male
  <input type="radio" name="gender" value="other">Other
  <span class="error">* <?php echo $genderErr;?></span>

// display submitted data
<?php
echo "<h3>Your Input:";
echo "<p>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $website;
echo "<br>";
echo $comment;
echo "<br>";
echo $gender;
echo "</p>"
?>