php validation to check text field is not working - php

I am trying to create a simple tax calcualtor and need to validate the both textfields so they are not empty and it doesn't appear to be working any tips?
if(isset($_GET['taxSubmit'])) {
$afterPrice = $_GET['taxPrice'];
$taxRate = $_GET['taxRate'];
$beforeTax = ($afterPrice * 100) / ($taxRate + 100);
if(!empty($_GET['taxPrice'.'taxRate'])){
echo "<h1>Price before tax = £".$beforeTax."<h1>";
} else {
echo 'All Fields Required';
}
}
Somebody asked for the markup so here it is:
<form method="get" action="watWk5.php">
<fieldset>
<legend>Without tax calculator</legend>
<label for="">After Tax Price</label>
<input type="text" name="taxPrice"/ value=<?php
if(isset($_GET['taxPrice'])){
echo $_GET['taxPrice'];
}
?>>
<label for="">Tax Rate</label>
<input type="text" name="taxRate"/ value=<?php
if(isset($_GET['taxRate'])){
echo $_GET['taxRate'];
}
?>>
<input type="submit" value="Submit" name="taxSubmit"/>
<button type="reset" value="Reset" name="clrButton">Clear</button>
</fieldset>

Each variable should have its own !empty() check
if(!empty($_GET['taxPrice']) && !empty($_GET['taxRate'])) {
//proceed
} else {
//throw error
}

Related

PHP - Validate if textbox has a value or not?

I want to validate if the textbox has a value or not. Right now what I have is a textbox that has a value but the output says it is empty here is it it is like nothing is being conditioned on the code please see me code, thank you
Full Code
-Here is the full code of my form please take a look thank you very much
<form>
<div class="row">
<form method="POST">
<div class="col-md-8">
<?php
$code = 'Code';
$code2 = 'PIN';
if(isset($_POST['btnSubcode'])) {
$lblCode = isset($_POST['lblQrTxt']) ? $_POST['lblQrTxt'] : '';
$code = $lblCode;
$code = explode(":",$code); // code = array("QR Code","444444444|123")
$code = explode("|",$code[1]); // code[1] = "444444444|123"
$code = trim($code[0]); // 444444444
$code2 = $lblCode;
$code2 = explode(":",$code2); // code = array("QR Code","444444444|123")
$code2 = explode("|",$code2[1]); // code[1] = "444444444|123"
$code2 = trim($code2[1]); // 123
}
?>
<div class="form-group">
<label class="form-control-label">code</label>
<input type="text" name="input" id="card-code" value='<?php echo $code ?>' class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-control-label">pin</label>
<input type="text" id="card-pin" value='<?php echo $code2 ?>' class="form-control" maxlength="3">
</div>
<?php
if(isset($_POST['txtQrtxt']) && $_POST['txtQrtxt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
<div class="caption">
<div class="jumbotron">
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
<textarea class="form-control text-center" id="scanned-QR" name="lblQrTxt"></textarea><br><br><br>
</div>
</div>
</form>
<div class="form-group float-right">
<input value="Topup" class="btn btn-primary topup-button">
</div>
</div>
</div>
</form>
<?php
$txtCodeqr = isset($_POST['txtQrtxt']) ? $_POST['txtQrtxt'] : '';
if (!empty($txtCodeqr)) {
echo "Text";
} else {
echo "Empty Textbox";
}
?>
my textbox
<input type="text" name='txtQrtxt' value='Hello World' class="form-control" >
You might be over complicating it. It is pretty simple.
<?php
if(isset($_POST['txt']) && $_POST['txt'] != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Additionally I would recommend you filter all input on post or get. Basically anything that gets information from a user.
Check here - http://php.net/manual/en/function.filter-input.php
<?php
$my_txt = filter_input(INPUT_POST, 'txt');
if(isset($my_txt) && $my_txt != '') {
echo "Text Present";
} else {
echo "Text Not Present";
}
?>
Also you need to add a submit button between your form tags. Like this.
<input type="submit" value="Submit">
Also you should have only one closing tag for every opening tag. This is called valid HTML.
For example a valid form is like
<form method="post">
First name:<br>
<input type="text" name="firstname" value="Mickey"><br>
Last name:<br>
<input type="text" name="lastname" value="Mouse"><br><br>
<input type="submit" value="Submit">
</form>
Ok I have made a simple php test file and tested it works. Your problem is:
You don't have a submit button. The $_POST will not be there if you do not submit a form first.
It would be easier to validate your textarea using javascript instead.
Here is my test file and it works:
<html>
<body>
<form method="POST">
<textarea name="txtQrtxt">
</textarea>
<input type="submit">
</form>
<?php
$var = $_POST['txtQrtxt'];
if (strlen($var)<=0) {
echo "Textarea empty";
} else {
echo "Textarea Okay";
}
?>
</body></html>

I am getting a really weird result on my php form output

Here is my code:
<h2> Simple Form </h2>
<form action="" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName"><br /><br />
<input type="submit">
</form>
<br />
Welcome,
<?php
echo $_POST['firstName'];
echo " ";
echo $_POST['lastName'];
?>
!
<hr>
<h2>POST Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_POST['postName'];
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$age = $_POST['age'];
if ($age >= 16) {
echo "You are old enough to volunteer for our program!";
} else {
echo "Sorry, try again when you're 16 or older.";
}
}
?>
<hr>
<h2>GET Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input type="hidden" name="p" value="includes/forms.php">
Name: <input type="text" name="getName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
echo $_GET['getName'];
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET") {
$age = $_GET['age'];
if ($age >= 16) {
echo "You are old enough to volunteer for our program!";
} else {
echo "Sorry, try again when you're 16 or older.";
}
}
?>
I have two forms. Both displaying the exact same thing, but one form using POST and one using GET.
I have gotten so close to finishing this off but now I have another small/weird issue.
The code technically works correctly, but here's the output explanation:
when I first open up the page the GET form already has the result "Sorry, try again when you're 16 or older." When I fill out the first 'simple' form, it displays the result correctly but then the POST form shows the "Sorry, try again..." result. Then, when I fill in the information and click submit, it displays the correct result and the other two forms are blank as they're supposed to be, and then the same result when I fill out the GET form.
Any help on this is much appreciated.
Try this code :
<h2> Simple Form </h2>
<form action="" method="post">
First Name: <input type="text" name="firstName">
Last Name: <input type="text" name="lastName"><br /><br />
<input type="submit">
</form>
<br />
Welcome,
<?php
if (isset($_POST['firstName']) && $_POST['lastName'])
{
echo $_POST['firstName'];
echo " ";
echo $_POST['lastName'];
}
?>
!
<hr>
<h2>POST Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form action="" method="post">
Name: <input type="text" name="postName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
if (isset($_POST['postName']))
{
echo $_POST['postName'];
}
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (isset($_POST['age']))
{
$age = $_POST['age'];
if ($age >= 16)
{
echo "You are old enough to volunteer for our program!";
}
else
{
echo "Sorry, try again when you're 16 or older.";
}
}
}
?>
<hr>
<h2>GET Form</h2>
<h3>Would you like to volunteer for our program?</h3>
<form method="get" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>">
<input type="hidden" name="p" value="includes/forms.php">
Name: <input type="text" name="getName">
Age: <input type="text" name="age"><br /><br />
<input type="submit">
</form>
<br />
Hello,
<?php
if (isset($_GET['getName']))
{
echo $_GET['getName'];
}
?>
!
<br>
<?php
if ($_SERVER['REQUEST_METHOD'] == "GET")
{
if (isset($_GET['age']))
{
$age = $_GET ['age'];
if ($age >= 16)
{
echo "You are old enough to volunteer for our program!";
}
else
{
echo "Sorry, try again when you're 16 or older.";
}
}
}
?>
Please try this. I hope it will help.
Replace
if ($_SERVER['REQUEST_METHOD'] == "POST") {
with
if (isset($_POST['age'])) {
Similarly,Replace
if ($_SERVER['REQUEST_METHOD'] == "GET") {
with
if (isset($_GET['age'])) {
When you first enter on page, default REQUEST_METHOD is GET so you should check if isset($_GET['age']) {
and here check if it is more than 16
}
also you should check this one
echo $_GET['getName']; and change on this
echo isset($_GET['getName']) ? $_GET['name'] : "";
You should also check $_POST request like this and your program will work correctly.

i am using two submit button one form in codeigniter it was worked well in chrome but iam using the firebox both button going to the else part

<body>
<div id='container'>
<pre>
<fieldset>
<legend>login</legend>
<?php echo validation_errors(); ?>
<form method="post" id="login" name="login">
username :<input type="text" name="uname" id="uname" value="<?php echo $this->session->flashdata('uname') ?>" ><br>
password :<input type="password" name="upass" id="upass">
<input type="checkbox" name="remember">Remember me
<input type="submit" value="login" class="submit" name="login"> <input type="submit" value="signup" name="signup">
</form>
</fieldset>
</pre>
<div><?php echo $this->session->flashdata('error'); ?></div>
</div>
<div id="error"></div>
</body>
controller:
public function view()
{
if($this->input->post("login"))
{
if($this->input->post('remember')=='on')
{
$uname=$this->input->post("uname");
$this->session->set_flashdata('uname',$uname);
}
$this->form_validation->set_rules('uname','username','trim|required');
$this->form_validation->set_rules('upass','password','required');
$data['title']='login page';
if ($this->form_validation->run() === FALSE)
{
$this->session->set_flashdata('error','enter username and password');
$this->load->view('stud_det/login',$data);
}
else
{
$data['result']=$this->stud_model->login();
if(!empty($data['result']))
{
$session=array(
'uname'=>$this->input->post('uname'),
'upass'=>$this->input->post('upass')
);
$this->session->set_flashdata($session);
$this->session->set_userdata($session);
$this->load->view('stud_det/view',$data);
}
else{
$this->session->set_flashdata('error','username or password is incorrect');
$this->load->view('stud_det/login',$data);
}
}
}
else{
$this->load->view('stud_det/index',array('title'=>''));
}
In your first if condition, you are loking for 'login' POST variable, however 'login' is the name of the submit input type. You have to test the post value 'uname' and 'upass'. Something like this:
if($this->input->post("uname") && $this->input->post("upass")) {
// Your code...
}
Other thing, you do not need define name to form tag. The name 'login' it is duplicated in form and input tags.

Trying to output data which has been input by user

I'm having issues trying to output data which a user has inputted into a form.. It's a 2 block form, I'm just trying to save the data into 2 variables and then echo the variables. But I don't understand where I'm going wrong. Any help appreciated.
<?php
echo $problem = "";
if(isset($_POST['submit']) && $_POST['submit']=="submit"){
if(!empty($_POST['eWeight']) && $_POST['eWeight']!=''){
$eWeight = mysqli_real_escape_string($conn, trim($_POST['eWeight']));
} else {
$problem .= "Please enter a weight. <br/>";
}
if(!empty($_POST['gym']) && $_POST['gym']!=''){
$gym = mysqli_real_escape_string($conn, trim($_POST['gym']));
} else {
$problem .= "Please enter time at gym. <br/>";
}
echo $eWeight, $gym;
}
?>
<?php
if($conn){
echo "connected";
}
echo $problem;
echo $eWeight;
?>
<form class="pure-form pure-form-stacked" name="contact_weight">
<label for="eWeight">Enter Weight: </label> <input type="number" id="eWeight" name="eWeight" placeholder="88" required/>
<label for="gym">Enter Time at Gym: </label> <input type="number" id="gym" name="gym" placeholder="60" required/>
<button class="submit" type="submit">Submit Form</button>
</form>
You can do something like this
<?php
echo $problem = "";
if(isset($_POST['submit'])){
if(!empty($_POST['eWeight']) && $_POST['eWeight']!=''){
$eWeight = mysqli_real_escape_string($conn, trim($_POST['eWeight']));
} else {
$problem .= "Please enter a weight. <br/>";
}
if(!empty($_POST['gym']) && $_POST['gym']!=''){
$gym = mysqli_real_escape_string($conn, trim($_POST['gym']));
} else {
$problem .= "Please enter time at gym. <br/>";
}
echo $eWeight, $gym;
}
if($conn){
echo "connected";
}
echo $problem;
echo $eWeight;
?>
<form class="pure-form pure-form-stacked" name="contact_weight" action="" method="post">
<label for="eWeight">Enter Weight: </label> <input type="number" id="eWeight" name="eWeight" placeholder="88" required/>
<label for="gym">Enter Time at Gym: </label> <input type="number" id="gym" name="gym" placeholder="60" required/>
<button name="submit" class="submit" type="submit">Submit Form</button>
</form>

Why this validation code does not work as expected?

I have a form and the action of the for m is same page.
I am trying to :
Show a thanks message upon the successful form submission
Show error messages next to the field where the error is detected
All the above must be shown in the same page.
My code is :
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
}
else {
?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
}
?>
I've limited the validation and showing only for first part in this QUESTION.
When I submit this form If there is NO any errors the I am getting the message Thanks, We have received your feed back
That's fine and works as expected.
When an error exists / the field Guest name is empty I am getting the message during the form submission Errors!
Please check the fields which have errors below. Error hints are in Red.
That's also fine.
But my form is just disappear when I get the above message. Why?
Also I want show that Please type your name! next to the field.
Try bellow code. I have removed else part and set flag with true/false to check from is valid or not.
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
$chkValidate = "true";
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
$chkValidate = "false";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';
$chkValidate = "false";
}
if($chkValidate == "true"){
echo 'Thanks, We have received your feed back';
}
}
?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?php if(!empty($errors) && $chkValidate != "false") { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
?>
Just remove else condition cause actually your form will not be display if $_POST["Ask_the_Question"] is set
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
}
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
The reason why is here:
<?php
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
}
} else {
// your form code will never be called if $_POST['Ask_the_Question'] is set
TO do what you want to achieve you probably want to do something like this instead:
<?php
$errors = array();
if (isset($_POST["Ask_the_Question"])) {
$guest_name = $_POST["guest_name"];
$title = $_POST["faq_title"];
$description = $_POST["faq_desc"];
$title = $_POST["faq_title"];
/* validation */
if (empty($guest_name)) {
$errors['guest_name'] = "Please type your name!";
}
if(!empty($errors)){ echo '<h1 style="color: #ff0000;">Errors!</h1><h6 style="color: #ff0000;">Please check the fields which have errors below. Error hints are in Red.</h6>';}
}
if(empty($errors)){
echo 'Thanks, We have received your feed back';
} else { ?>
<form action="index.php" method="post" class="booking_reference">
<input type="text" name="guest_name" placeholder="Your Name" value="<?PHP if(!empty($errors)) { echo $guest_name;} ?>" />
<?php if(isset($errors['guest_name'])) { echo '<span style="color: red">'.$errors['guest_name'].'</span>'; } ?>
<input type="email" name="guest_email" placeholder="Your email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" required />
<input type="text" name="faq_title" placeholder="FAQ Title"/>
<input type="text" name="faq_desc" placeholder="FAQ Description"/>
<input type="submit" name="Ask_the_Question" value="Ask the Question" />
</form>
<?php
}
}
?>
Other answers are fine, but just to clarify what happens.
But my form is just disappear when I get the above message. Why?
Your form disappear because if you pass the first if you can't get to your else.
if (isset($_POST["Ask_the_Question"])) {
...
} else {
xxx;
}
That means if you want to see your form you have to put it somewhere it can be shown like elseif (with more restrictions), or ifs inner or outer.
if (isset($_POST["Ask_the_Question"]) && empty($errors)) {
...
} elseif (isset($_POST["Ask_the_Question"]) && !empty($errors)) {
...
} else {
...
}
Also I want show that Please type your name! next to the field.
To show all errors you could use eg. foreach anywhere you want to show them.
foreach ($errors as &$error) {
echo "Error: $error<br />\n";
}
Btw be careful with the empty(); function.

Categories