Validation of data submitted by the form

Asked

Viewed 50 times

0

I am validating a form and I face a problem that I cannot solve. First, I make a foreach and check if there are any $_POST empty, if any, executes: $error[$key] = "*";. Then, below the input, I check if the user clicked on Submit and whether the variable $error[$key] was set, if yes, prints "*"; <br>, but 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>"; ?>

1 answer

0

How are you assigning the value of input for $key, replace the

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

for

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

Complete:

<?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>
  • It hasn’t changed at all, I think it’s that because $_POST is an array, it doesn’t matter if it looks for key or value, both are empty

  • Are you sure, man? I took the test here and it worked right.

  • I discovered the mistake, I was putting the foreach after the input... the code is right, I was stupid. Thanks for answering and sorry for wasting your time

Browser other questions tagged

You are not signed in. Login or sign up in order to post.