I am working on a small project where I need to validate (server side) a form. With the following code it works well to show the messages "There is A problem" or "There is NO problem". I want now to show the messages like "The name is missing " when the name is missing or "The first name is not valid" when it is not. If many errors occurred, it would show multiple message. Every message must be shown in the same page as the form. I do not know if my explanations are clear.
<?php
echo $_SESSION["errorMsg"];
session_unset("errorMsg");
?>
<form method="post" action="test1.php">
<table class="contactInformation">
<tbody>
<tr>
<td>
<label for="">Nom</label>
</td>
<td>
<input type="text" name="lastName"/>
</td>
</tr>
<tr>
<td>
<label for="">Prénom</label>
</td>
<td>
<input type="text" name="firstName"/>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Envoyer la commande">
</form>
<?php
if (!empty($_POST["lastName"])) {
$lastName = trim($_POST["lastName"]);
if (strlen($lastName) < 2 || 50 < strlen($lastName)) {
$errors = "The name is not valid";
}
}
else {
$errors = "The name is missing";
}
if (!empty($_POST["firstName"])) {
$firstName = trim($_POST["firstName"]);
if (strlen($firstName) < 2 || 50 < strlen($firstName)) {
$errors = "The firstname is not valid";
}
}
else {
$errors = "the firstname is missing";
}
if ($errors != "") {
$_SESSION["errorMsg"] = "There is A problem";
header("Location: test2.php");
exit();
}
else {
$_SESSION["errorMsg"] = "There is NO problem";
header("Location: test2.php");
exit();
}
?>
$errorsand add a value everytime theres an error.