Reputation: 59
I have the following code :
if(isset($_POST['submit'])){
if (! isset($_POST['firstname'])) {
$error[] = "Please fill out all fields";
}
if (! isset($_POST['surname'])) {
$error[] = "Please fill out all fields";
}
........
with validation:
if (strlen($_POST['firstname']) < 2){
$error[] = 'First name cannot be empty';
}
if (strlen($_POST['surname']) < 2){
$error[] = 'Please provide your surname';
}
......
More checks are made with the database....
This checks for errors and displays them in one go:
if(isset($error)){
foreach($error as $error){
echo '<p class="error-login">'.$error.'</p>';
}
}
While this is working fine, I would like errors to be shown under each input box where there is an error happening.
I don't want to change the entire code, just want to make the necessary changes to this one, which I am incapable of doing myself.
Is putting them in array the only approach here or is there a simpler way ?
Thanks.
Upvotes: 1
Views: 76
Reputation: 54841
The approach is - add errors to $error
under a certain key, I presume - name of the input field:
if(isset($_POST['submit'])){
// I use key `all` for errors that don't belong to any field
if (! isset($_POST['firstname'])) {
$error['all'] = "Please fill out all fields";
}
if (! isset($_POST['surname'])) {
$error['all'] = "Please fill out all fields";
}
if (strlen($_POST['surname']) < 2){
$error['surname'] = 'Please provide your surname';
}
In your html markup:
// general errors, not related to inputs
if(isset($error['all'])){
foreach($error['all'] as $err){
echo '<p class="error-login">'.$err.'</p>';
}
}
<input type="text" name="surname" />
<?php
if(isset($error['surname'])){
foreach($error['surname'] as $err){
echo '<p class="error-login">'.$err.'</p>';
}
}
Upvotes: 1