php


PHP - CSS - 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.
Thanks in advance! :)
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 slighly 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, no need to say ^^
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.

Related Links

Getting no data from SQL in PHP for android parsing
wkhtmltoimage give a small image output but using high browser resolution
“The custom token format is incorrect” How to get a custom token with a correct format using jwt/php?
where is the error in my code that make the sql query stop working
How to get the values in between below string using mysql query [closed]
How do I handle unable to send email on Laravel 4 on non existing email address
Save image from PHP URL - returns empty image
Cant use pivot in MySQL. Get 1064 error
php session variables on multiple pages not working
php - my variables are not showing [duplicate]
WordPress: Fetch posts by meta_value and order by the same?
Laravel find missing row inside the table
Eloquent Laravel foreign key to spivot table
Namespace breaking call to Composer imported classes
vendor class not found in laravel 5.3
Two mysql query searches on same page?

Categories

HOME
hpoo
elasticsearch
artificial-intelligence
eclipse-plugin
adfs3.0
android-fragments
workflow
redmine
consul
tabs
biztalk-2010
swift2
material-components
navigation
graphql-js
pyresttest
gtk
lc3
heuristics
match
phpstorm-2017.1
nest-api
pinterest
android-5.1.1-lollipop
hidden
cocos2d-android
boomi
adobe-illustrator
spring-shell
backtracking
conda
quantitative-finance
candlestick-chart
eclipse-emf
pubxml
beego
fstar
running-object-table
echosign
python-imageio
annotation-processing
django-import-export
sendmessage
substance
rspec-rails
om-next
cloudera-quickstart-vm
unification
tidal-scheduler
oauth2
klee
coverage.py
yoast
dredd
cloudwatch
rm
brightscript
ilrepack
jgrapht
extjs4.1
android-webservice
gnome-terminal
ptvs
word-2016
dymola
hmmlearn
nrf51
oracle-fusion-apps
clp
visual-studio-monaco
svnserve
nunit-console
callouts
codecharge
processor
preferenceactivity
psd
openmrs
ui4j
helm
msgpack
astropy
ora-04091
bjam
apple
supercomputers
org-babel
explain
r.java-file
maven-shade-plugin
mod-auth-openidc
google-hangouts
thoughtworks-go
dc
global-scope
inequality
nidaqmx
otl
forio-contour
commenting
gpu-programming
windows-taskbar
strdup
pbkdf2
mousemotionlistener
sql-view
disjoint-union
html-frames
days
xalan
spark-view-engine
sfinae
taskkill
autosize
server-variables
botnet
css-friendly
digiflow
airprint
downgrade
ccl
solandra
tessellation
odac
oracle-pro-c
data-retrieval
eai

Resources

Encrypt Message