menu

Questions & Answers

Simple form validation test - Change border color for empty result

I have this simple login form I'm testing. I'm using PHP, XAMPP, testing in Chrome.

This is the code for the form:

<form action="login.php" method="POST">

    <label>User: </label>
    <input type="text" name="user" <?php if($errors){echo 'style="border:1px solid red;"';}?>>
    <?php echo '<script>console.log("Value for $errors: '.$errors.'")</script>';?> 

    <label>Password: </label>
    <input type="password" name="password" <?php if($errors){echo "style='border:1px solid red;'";}?>>

    <div class="text-center">
        <button type="submit" name="submit">Sign in</button>
    </div>
</form>

This code is part of login.php, and at the very beginning, I have the following PHP lines:

<?php

session_start();

$user = "";
$password = "";
$errors = 0;

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

    if(isset($_POST['user'])){
        if(!empty($_POST['user'])){
        $user = $_POST['user'];
        }
    }else{
        $errors = 1;
    }

    if(!empty(isset($_POST['password']))){
        $password = $_POST['password'];

    }else{
        $errors = 1;
    }

    $_SESSION['user'] = $user;
    $_SESSION['password'] = $password;

}

?>

The action attribute in the form calls itself (calls the same file --> login.php) In the PHP script, I try to achieve that if the form was submitted, then perform all the validation, etc. As regards the simple validation, I try assign the POST values received to the variables, IF what was received EXISTS AND IT'S NOT EMPTY. If empty or non-existant --> $errors = 1;

The thing is.. if there are errors with the two inputs, I want them to change their border color to red. So I did:

<label>User: </label>
<input type="text" name="user" <?php if($errors == 1){echo 'style="border:1px solid red;"';}?>>
<?php echo '<script>console.log("Value for $errors: '.$errors.'")</script>';?>

The last lines I've added to try to print in console the value of $errors, which always shows 0.

I've tried a little redirection using empty($user), and when submitting the form without touching the inputs, it indeed shows that the values are empty. Still, I don't fully get why being empty, $errors always has value 0.

Comments:
2023-01-17 23:01:03
Out of curiosity, why are you using 0 and 1 instead of true and false? Answer posted anyway
2023-01-17 23:01:03
Mainly because I'm just learning, I've actually tried true/false when trying to print to console, but as it returned nothing, then I kept the numbers
2023-01-17 23:01:03
I'm not sure why you're trying to log these in the JS console. Just use var_dump() instead. var_dump( $errors );
2023-01-17 23:01:04
@NathanDawson because when I hit submit button, it refreshes... so I can't see the var_dumps on screen :/ I don't know how to actually submit, get that there are errors, and get back to the login with the red borders in the inputs
Answers(2) :

There's a flaw in the way you're checking the values.

if ( isset( $_POST['user'] ) ) {
    if ( ! empty( $_POST['user'] ) ) {
        $user = $_POST['user'];
    }
} else {
    $errors = 1;
}

Your form has a field titled user which is being submit therefore $_POST['user'] will be set. If it is set then it doesn't matter whether or not it's empty, your code won't change $error to 1. You have a nested loop which isn't accounting for that.

empty() is going to check if it's set too so you don't need isset().

if ( ! empty( $_POST['user'] ) ) {
    $user = $_POST['user'];
} else {
    $errors = 1;
}

The same should apply to password. Combining empty() with isset() doesn't make sense. Copy the approach from user.

Comments:
2023-01-17 23:01:04
Hi! Yes, just moments ago I've tried another way of writing empty() with isset() and was working fine (with $errors changing the value, but not the border color), but I see what you mean, and have changed the code to what you posted, thank you very much :) It still doesn't work though, the border color of the inouts is not changing after submit :/

Not needed to go back on @Nathan-Dawson comment/answer about the way you need to check values, it's all said. Here's a slightly different approach: I added warning messages before/after so you can improve user's experience and it (hopefully) shows you how you can check values.

PHP side

<?php

error_reporting(E_ALL); ini_set('display_errors', 1);

$errors = 0; // so you don't get 'red' applied without submitting the form

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

if(isset($_POST['user'])){ // check for POST'd value
    if(!empty($_POST['user'])){
    $user = $_POST['user'];
    // $errors = 0; <- $errors would remain '0' but not needed, just for the logic
    } else {
    $errors = 1; // form is processed but $user is POST'd empty
    }
} else {
    $errors = $errors; // needed if one field is set but not the other one
   // so we don't set $errors back to '0'
}

// same logic applies to 'password' -> no need to comment it out again :)

if(isset($_POST['password'])){
    if(!empty($_POST['password'])){
    $password = $_POST['password'];
    } else {
    $errors = 1;
    }
} else {
    $errors = $errors;
}

// added this to show users if they forgot something or not
if($errors == 0) {
$warning_mess = "Form fields have been filled, thx !";
} else { 
$warning_mess = "Please fill all fields before submitting."; 
}

// before submitting, give users a warning about fields
} else { $warning_mess = "Form fields need to be filled"; }

?>

the FORM side

<input type="text" name="user"
<?php if($errors == "1"){ echo 'style="border:1px solid red;"'; } ?> />

I just added the checking upon value of '$errors' with == to make sure we had a 0/1 -> it can be useful if you want later to make a difference and set up a customized error handling message for each field.

Of course, you need to trim and check and sanitize all data coming from users

Comments:
2023-01-17 23:01:04
Hi @OldPadawan! Nice, thanks! I can see errors now! But this line --> $errors = 0; // so you don't get 'red' applied without submitting the form does all the opposite :/ The borders appear in red without submitting. I've tried a var_dump($errors); right after that line, and prints int(0), but then at the end I print the variable again and it's already 1 (without submitting)
2023-01-17 23:01:04
not when I tested though... It's set up in order to not have red bordered inputs without submitting, when you 1st reach the page (or if fields are ok). Do you have any other stuff in this code ?
2023-01-17 23:01:04
Thank youuu! It's working correctly now! :D just opened and closed the window.. Thanks for the comments and the explanation! :D