Reputation: 13
I have a simple registration form on my site. There are various validation rules regarding empty fields, incorrect characters etc.
I have a variable called $error
, which is initally set to 0 but if there is a validation error it sets to 1 and another variable $error_message
displays the error message itself. Below is an example:
if (strlen($firstName) == 0) {
$error = 1;
$error_message = "<br/> First name is required";
}
if (!preg_match($expName, $firstName)) {
$error = 1;
$error_message = 'The First Name you entered does not appear to be valid.<br />';
}
if (strlen($lastName) == 0) {
$error = 1;
$error_message = "<br/>Last name is required";
}
if (!preg_match($expName, $lastName)) {
$error = 1;
$error_message = 'The Last Name you entered does not appear to be valid.<br />';
}
Whenever there is an error, the registration fails and the user is notified of what error it is, no last name, incorrect characters on first name, etc etc. The problem that I have is that only one error message displays, even if the user has had multiple validation errors in their form.
My specific question is: How do I display multiple error messages, if there are indeed multiple error messages?
I have thought about setting $error = ()array;
and using a while loop to possibly loop through and display each error message but I am unsure if I can keep the 0 and 1 for error flagging, if that makes sense.
Is this possible?
I have looked through a few answers on this topic but they seem to relate to displaying multiple rows from a database, which I am not doing on this particular page.
Below is the container/column which the error message should be displayed (PHP generated).
<div class='icon-center-check-circle'>
<i class='fas fa-times-circle'></i>
</div>
<div class='col-md-succ'>
<br>Error with registration:</br>
<br>$error_message</br>
<br><a href = 'register.php' <button type = 'Submit' name = 'Submit'>Try Again</button></a></br>
</div>
</div>
</div>
Thanks for your time and any advice you can share!
Upvotes: 1
Views: 888
Reputation: 5191
Store your errors in the $error_message
array then simply use empty
to test whether or not there are any errors. No need to set a separate flag.
$error_message[] = 'Last name is required';
Then, to display them:
<?php
if (!empty($error_message)) {
echo '<br>Error with registration:</br>';
foreach ($error_message as $error) {
echo '<br>' . $error . '</br>';
}
}
?>
Upvotes: 1
Reputation: 1473
just a small example:
<?php
$errors = [];
$someVar = '';
if (empty($someVar)) {
$errors[] = 'need input';
}
if (!false) {
$errors[] = 'another error';
}
$errorsOccured = count($errors) > 0;
foreach ($errors as $error) {
echo $error . PHP_EOL;
}
If you use an array, you can check at the end if errors occured. (if there were no errors, the array would be empty.) The running code can be found here:
Upvotes: 0