i

PHP Tutorial

PHP Form Required Validation

When we need input fields to be mandatory then we need to do required validation. For this, we need to create error variables and add if else statements to give the output based on validations. PHP empty() function is used to the $_POST variable value is empty or not. If the value is blank then error message is displayed else the values are sent through the php script.

For example, if we create a form that inputs name and email address from the users. And the user submit the button without any inputs then required error message is displayed on the form.


$name_Err = $email_Err = “”; //setting blank value to error variables.

$name = $email = “”; //defining and setting blank value to variables.

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

  if (empty($_POST["email"])) {
    $email_Err = "Email is required";
  } else {
    $email = $_POST["email"];
  }

}

?>