PHP Form Required

In the previous chapter, all input fields were optional. But This chapter shows how to make input fields required and create error messages if needed.

Using PHP forms you can set certain fields to be required and display error messages if they aren't filled in upon submission.


Steps:


  1. Check if the form is submitted.
  2. Validate required fields.
  3. Display error messages if fields are empty.
  4. Retain user input after form submission.
Basic Example of Required Fields in PHP Form Validation
<?php
// Define variables and set empty values
$name = $email = "";
$nameErr = $emailErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Check if Name is empty
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}

// Check if Email is empty
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}
}

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

<!DOCTYPE html>
<html>
<head>
<title>PHP Required Field Validation</title>
</head>
<body>

<h2>PHP Required Field Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name" value="<?php echo $name; ?>">
<span style="color: red;">* <?php echo $nameErr; ?></span><br><br>

Email: <input type="text" name="email" value="<?php echo $email; ?>">
<span style="color: red;">* <?php echo $emailErr; ?></span><br><br>

<input type="submit" name="submit" value="Submit">
</form>

<?php
// Display success message if no errors
if ($_SERVER["REQUEST_METHOD"] == "POST" && $nameErr == "" && $emailErr == "") {
echo "<h3>Form Submitted Successfully</h3>";
echo "Name: " . $name . "<br>";
echo "Email: " . $email . "<br>";
}
?>

</body>
</html>

Try it yourself


How It Works


  1. Check for Required Fields:
  • if (empty($_POST["name"])) → If the field is empty, it sets an error message.
  1. Sanitize Input (test_input())
  • trim() removes extra spaces.
  • stripslashes() removes backslashes.
  • htmlspecialchars() prevents XSS attacks.
  1. Display Error Messages:
  • If a field is empty, a red error message appears next to it.
  1. Retain User Input:
  • The value="<?php echo $name; ?>" ensures that after submitting, the entered data remains.



Output Examples


Before Submission:



If Name and Email Are Left Empty:



After Successful Submission:



Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.