Validation of data submitted by the form

0

I am doing the validation of a form and I am facing a problem that I can not solve. First, I make a foreach and check if there is any $_POST empty, if any, it executes: $error[$key] = "*"; . Then, below the input , I check if the user has clicked on submit and if the variable $error[$key] has been set, if so, it prints "*"; <br> , however nothing happens.

foreach :

foreach ($_POST as $key => $value) {
   if(empty($_POST[$value])) {
      $error[$key] = "*";
      $valida = false;
   }
}

input :

<input type="text" class="demoInputBox" name="firstName" value="<?php if(isset($_POST['firstName'])) echo $_POST['firstName']; ?>">
<?php if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($error['firstName'])) echo "<label style = 'color: #ff0000'>" . $error['firstName'] . "</label>"; ?>
    
asked by anonymous 04.09.2017 / 01:03

1 answer

0

Since you are assigning value of input to $key , replace

if(empty($_POST[$value])) {
  ...
}

by

if(empty($_POST[$key])) {
  ...
}

Completed:

<?php
foreach ($_POST as $key => $value) {
    if(empty($_POST[$key])) {
        $error[$key] = "*";
        $valida = false;
    }
}
?>
<form method="post">
    <input type="text" class="demoInputBox" name="firstName" value="<?php if(isset($_POST['firstName'])) echo $_POST['firstName']; ?>">
    <?php if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($error['firstName'])) echo "<label style = 'color: #ff0000'>" . $error['firstName'] . "</label>"; ?>
    <input type="submit">
</form>
    
04.09.2017 / 02:01