PHP validation showing wrong icon

Viewed 81

I am new to PHP. I am here trying to show error icon when validation fails

PHP

<?php
// define variables and set to empty values
$nameErr = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
  } 
}
?>

HTML

<div class="<?php if (empty($nameErr)){ echo 'success-validate';} else { echo 'failure-validate'; } ?>">                
</div>

Here, I am always getting the success-validate icon when the page loads for first time. But when I click the submit button, the validation is working fine. Please help me resolve the issue.

1 Answers

So, the problem here is that you have 3 states (valid, no-valid and no-validation-used) instead of two as you think of at first.

So, the simplest solution can be to add another flag which tells that validation has started, eg:

// define variables and set to empty values
$nameErr = "";
$name = "";
$validationApplied = false;  // here
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $validationApplied = true;
  
  if (empty($_POST["name"])) {
    $nameErr = "Name is required";
  } else {
    $name = test_input($_POST["name"]);
  } 
}

In your html you then can check both variables like this:

<div class="<?php if ($validationApplied) { echo empty($nameErr) ? 'success-validate' : 'failure-validate'; } ?>">                
</div>

Another solution can be to check both $nameErr and $_SERVER["REQUEST_METHOD"] == "POST". It's the same as above approach, just instead of distinct flag you check REQUEST_METHOD:

<div class="<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { echo empty($nameErr) ? 'success-validate' : 'failure-validate'; } ?>">                
</div>
Related