'Forms with errors, how not to lose data in PHP

a little question that I hope can be answered even if I think that natively with PHP, nothing can be done.

I have a form with various input fields, obviously the frontend rules in javascript at the time of submission to report the required fields are not enough.

I have implemented a server side backend check before the form is submitted if there are any errors the form is stopped and x error alerts are displayed how many errors were encountered.

Virtually perfect.

Except that the form is made up of 200 fields and even if the user makes a mistake, boom the whole form is devoid of data.

So my question, is it possible with PHP, to display error alerts but without losing the previously written values?

code:

<?php
ob_start();
session_start();

/*VARIABILE GLOBALE DI ERRORE*/
$error = array();

if (isset($_POST['submit'])) {

    $name = $_POST['name'];

    /*CHECK NAME INPUT*/
    if (empty($name)) {
        $error[] = '<div class="alert alert-danger" role="alert">Name is a required field</div>';
    } else {
        if (preg_match("~[0-9]+~", $name)) {
            $error[] = '<div class="alert alert-danger" role="alert"> Name cannot contain numbers </div>';
        }
    }


    if (count($error) > 0) {

        /*show error with echo implode( $error);*/

    } else {
        
        /*run query*/
    }
}
?>

<?php echo implode( $error); ?>

<form  action="YOUR_PAGE.PHP" method="post">
    <input name="name" type="text">
    <input name="submit" type="submit" value="submit">
</form>

the goal would be to show the alerts, but without losing all the data written in the various fields that make up the form

POSSIBLE SOLUTION

<input name="name" type="text" value="<?php if ($error > 0) echo strip_tags($_POST['name']) ?>>

In this way, I display alerts and incorrect entry.

Is this the best solution?

php


Solution 1:[1]

I might be late, but I was thinking... why don't you do your validation in JS?

Below I have an example that you can go through and see how it works.

It is a bit chaotic and rushed but it does what you want & more. It first tests if the values for the 3 fields that I have (name, email, password) are provided and then checks if the name contains letters only, email contains a valid email format and that the password contains 8 or more charatcers.

If all those conditions are met, it allows the form to be submitted to your php script, if not it shows the error message without refreshing the page. Meaning you won't lose your data in the form.

//we get the form element after page has loaded
var form = document.getElementsByTagName('form')[0];

//when the form is being submitted we do our validation here
form.addEventListener('submit', function(e) {
  //this gets the total number of input fields to be submitted
  var inputs = document.getElementsByClassName('input-field').length;
  /*here we have an array of error messages for input fields that will contain wrong information*/
  var errors = ['name cannont contain numbers', 'email address provided is invalid', 'password must not be less than 8 characters'];
  for (let i = 0; i < inputs; i++) {
    /*our input fields have class names 0,1,2. We'll use this forloop to check if all these input fields have a value, if not,  we display an error message and break the loop*/
    if (document.getElementsByClassName(i)[0].value == '') {
      //firstly we prevent the form from being submitted
      e.preventDefault();
      /*if the value for a field is not provided we get the name attribute of the input field and create an alert message that we display on the <p> element under our form*/
      let errorMsg = document.getElementsByClassName(i)[0].name + ' is required';
      //here we display the message
      document.getElementById('status').innerText = errorMsg;
      //and break the loop
      break;
      //if the value is provided, below we have another if statement that will check if the value contains correct characters
    } else if (testInputValue(i) == false) {
      //firstly we prevent the form from being submitted
      e.preventDefault();
      //then we get the error from the errors array and display it
      document.getElementById('status').innerText = errors[i];
      //while breaking the for loop to stop validating input fields
      break;
    }
  }
});

/*this is the function that tests our input values for valid values*/
function testInputValue(inputClass) {
  if (inputClass == 0) {
    //this will return false if the name includes characters that are not alphabets
    return /^[a-zA-Z ]+$/.test(document.getElementsByClassName(inputClass)[0].value);
  } else if (inputClass == 1) {
    //this will return false if the email address is invalid
    return /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(document.getElementsByClassName(inputClass)[0].value);
  } else if (inputClass == 2) {
    //this will test if the password contains characters not less than 8
    return document.getElementsByClassName(inputClass)[0].value.length < 8 ? false : true;
  }
}
#status {
  background-color: white;
  color: red;
  font-size: 18px;
}
<form action="" method="post">
  <input type="text" name="name" class="input-field 0" placeholder="Name..." /><br /><br />
  <input type="email" name="email" class="input-field 1" placeholder="Email..." /><br /><br />
  <input type="password" name="password" class="input-field 2" placeholder="Password..." /><br /><br />
  <input type="submit" name="submit" value="Submit Form" /><br />
</form>

<p id="status"></p>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Relcode