I am new to PHP. I am here trying to show error icon when validation fails
PHP
<?php
// define variables and set to empty values
$nameErr = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
}
?>
HTML
<div class="<?php if (empty($nameErr)){ echo 'success-validate';} else { echo 'failure-validate'; } ?>">
</div>
Here, I am always getting the success-validate icon when the page loads for first time. But when I click the submit button, the validation is working fine. Please help me resolve the issue.
So, the problem here is that you have 3 states (valid, no-valid and no-validation-used) instead of two as you think of at first.
So, the simplest solution can be to add another flag which tells that validation has started, eg:
// define variables and set to empty values
$nameErr = "";
$name = "";
$validationApplied = false; // here
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$validationApplied = true;
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}
}
In your html you then can check both variables like this:
<div class="<?php if ($validationApplied) { echo empty($nameErr) ? 'success-validate' : 'failure-validate'; } ?>">
</div>
Another solution can be to check both $nameErr and $_SERVER["REQUEST_METHOD"] == "POST". It's the same as above approach, just instead of distinct flag you check REQUEST_METHOD:
<div class="<?php if ($_SERVER["REQUEST_METHOD"] == "POST") { echo empty($nameErr) ? 'success-validate' : 'failure-validate'; } ?>">
</div>
Related
This is my Form - This an Include File.
form_file.php
<section class="container-sm">
<form method="post" class="par-form">
<h3 class="par-h2">John Doe Form</h3>
<p><label class="single-label" for='user_firstname'>Name: <a id='user_firstname_label'></a></label>
<input class="par-input form_login" maxlength="15" name="user_firstname" required value="<?=$obVaga->user_firstname?>" ></input><span class="error">*<?php echo $nameErr;?></span></p>
<p><label class="single-label" for='user_secondname'>Surname: <a id='user_secondname_label'></a></label>
<input class="par-input form_login" maxlength="40" name="user_secondname" required value="<?=$obVaga->user_secondname?>" ></input></p>
<p><label class="single-label" for='user_email'>E-mail: <a id='user_email_label'></a></label>
<input class="par-input form_login" maxlength="40" name="user_email" required value="<?=$obVaga->user_email?>" ></input></p>
<button type="button" onclick="sendData()" class="par-button" id='user_button_sendData'>SEND</button>
</form>
</section>
This is the template page that receives the Form file
single-add.php
<?php
/**
* Acess the composer library
*/
require __DIR__.'/vendor/autoload.php';
/**
* Use a Classe VAGA
*/
use \App\Entity\Vaga;
$obVaga = new Vaga;
if (isset($_POST['user_firstname'],$_POST['user_secondname'],$_POST['user_email'])) {
$obVaga->user_firstname = $_POST['user_firstname'];
$obVaga->user_secondname = $_POST['user_secondname'];
$obVaga->user_email = $_POST['user_email'];
$obVaga->user_cadastrar();
}
?>
<!-- Receive the contents of the form include form_file.php -->
<?php include __DIR__.'/appincludes/form_file.php' ?>
This is the Class page that receives the data
Vaga.php
<?php
namespace App\Entity;
/**
* Use a Classe Database
*/
use \App\Db\Database;
use PDO;
class Vaga{
// #var Integer
public $user_id;
// #var String
public $user_firstname;
// #var String
public $user_secondname;
// #var String
public $user_email;
// #var String
public $nameErr;
// #var Boolean
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user_firstname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["user_firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["user_secondname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["user_secondname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["user_email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
public function user_cadastrar(){
// DEFINIR A DATA
// INSERT STRINGs IN THE TABLE
$obDatabase = new Database('tb_partner');
$this->id = $obDatabase->insert([
'user_firstname' => $this->user_firstname,
'user_secondname'=> $this->user_secondname,
'user_email' => $this->user_email
]);
}
}
I´m trying to use this script to validate the fields, but I am stuck. I`m trying to execute this script through the class file Vaga.php
public function par_add_validate(){
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user_firstname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["user_firstname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["user_secondname"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["user_secondname"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["user_email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
};
}
I putted the Var $nameErr in the form_file.php where it should display an echo string IF the field is empty or with not acceptable letters.
This is the result in the debug.log file:
[18-Aug-2021 16:44:07 UTC] PHP Notice: Undefined variable: nameErr in C:\xampppserver2\htdocs\project\appincludes\form_file.php on line 15
Line 15:
<input name="user_firstname" required value="<?=$obVaga->user_firstname?>" ></input><span>*<?php echo $nameErr;?></span></p>
What am I doing wrong or what is missing?
I believe you have some lines missing here:
// #var Boolean
if ($_SERVER["REQUEST_METHOD"] == "POST") {
Otherwise you've put some logic code right inside your class (without method) which should result in a Parse error. Also why is there #var Boolean with no boolean property following?
Given that you wrap all that code in a method, you still have several issues. First, you can't access $nameErr directly. Instead, you want $this->nameErr.
And in form_file.php you also have no variable called $nameErr. You have nameErr as a property of $obVaga object though. You can access it using $obVaga->nameErr.
I'm starting to learn PHP and have the code below, which includes a connection to the database from a db.php file, which then runs a query which uses HTML form data that is added to a MYSQL database.
In the code below there is an if statement that means the $firstname field must have content. If I have a larger form and want to ensure every form field is filled in, is there a PHP function where I can select all form fields with a "name" attribute (or something similar)? I appreciate I could write out the if statement x number of times for each field but I was thinking there must be an inbuilt PHP function for this? But I couldn't see anything in the PHP docs?
Any help would be wonderful.
<?php include "db.php"; ?>
<?php
if (isset($_POST['submit'])) {
$firstname = $_POST['first-name'];
$email = $_POST['email'];
if ($firstname == "" || empty($firstname)) {
echo "This field should not be empty";
} else {
$query = "INSERT INTO user(firstname, email) VALUE('{$firstname}', '{$email}')";
$add_name_query = mysqli_query($connection, $query);
if (!$add_name_query) {
die('QUERY FAILED' . mysqli_error($connection));
}
}
}
?>
You could build your own function to make it a little more "dry".
<?php
$firstname = $_POST['first-name'];
$email = $_POST['email'];
$anotherField = "Something";
$andOneMoreField = "Nothing";
function checkInputField($inputField) {
if($inputField == "" || empty($inputField)) {
echo 'This field should not be empty';
return false;
} else {
return true;
}
};
if(
checkInputField($firstname) &&
checkInputField($email) &&
checkInputField($anotherField) &&
checkInputField($andOneMoreField)
// and so on...
) {
echo "Open doors for SQL-Injection";
// db-handling
}
?>
But this is only as food for thought for further learning. This is neither nice code nor a recommendation for implementation.
Another way to do the same:
<?php
function isEmptyField($value) {
return (trim($value) == "" || empty($value)) ? true : false;
}
$fieldNames = array('first-name', 'email'); //You can add others fields name here.
$fieldsOk = true;
foreach($fieldNames as $fieldName) {
if(! array_key_exists($fieldName, $_POST) || isEmptyField($_POST[$fieldName])) {
echo "The field {$fieldName} should not be empty! \r\n";
$fieldsOk = false;
//break; //You could break the validation if a field is empty.
}
}
if($fieldsOk) {
//TODO: INSERT QUERY!
}
?>
But I think you will need others validations for each field according to their data types.
I has read all the various post on StackOverflow regards this same but that was not helpful ...
Php script not shows error alert when text box empty or in invalid pattern. I know only empty script which I mention below but I don't known How I add pattern error also.
Also when textbox empty it not show error why? Please help. Please don't mark as it is duplicate because I read various post but same issue that is why I posted a threads. Please help in full script.
Advance thank you..
<?php
if(isset($_POST['submit']))
{
$name= $_POST['name'];
if (!($name))
{
$m1 = "<Div class="alert">Enter your Name</Div>" ;
}
$email= $_POST['email'];
if (!($email))
{
$m2 = "<Div class="alert">Enter Your Email"</Div> ;
}
$_SESSION['name'] =$name;
$_SESSION['email'] =$email;
$_SESSION['otp']=$rndno;
header( "Location: next-page.php" );
}
?>
In HTML Body
<div>
<?php if(isset($m1)) { echo $m1; } ?>
<?php if(isset($m2)) { echo $m2; } ?>
</div>
Try This code it is runnable
<?php
if(isset($_POST['submit']))
{
$name= $_POST['name'];
if ( $name == '')
{
echo $m1 = "<script type='text/javascript'>alert('Please Enter Your Name');</script>" ;
}
$email= $_POST['email'];
elseif ( $email == '')
{
echo $m2 = "<script type='text/javascript'>alert('Enter Your E-mail');</script>" ;
}
$_SESSION['name'] =$name;
$_SESSION['email'] =$email;
$_SESSION['otp']=$rndno;
else{
header( "Location: next-page.php" );
}
}
?>
Right now, posting a snippet of what I wrote:
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
Every single time when I try to post the snippet above or a variation of it, it literally blanks out my page.
Question is, is the code I wrote above a good way to compare two email addresses via text fields?
And why does it blank out my entire page every time?
Here's a bit of further context if that's more helpful (let me know you want the entire page):
<?php
session_start(); //allows use of session variables
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["nights"])) {
$nightsErr = "# of nights are required";
} else {
$nights = test_input($_POST["nights"]);
}
if (empty($_POST["arrivals"])) {
$arrivalsErr = "Time of arrival is required";
} else {
$arrivals = test_input($_POST["arrivals"]);
}
if (empty($_POST["male"])) {
$maleErr = "# of people (gender female) required";
} else {
$male = test_input($_POST["male"]);
}
if (empty($_POST["female"])) {
$femaleErr = "# of people (gender female) required";
} else {
$female = test_input($_POST["female"]);
}
if (empty($_POST["rooms"])) {
$roomsErr = "# of rooms required";
} else {
$rooms = test_input($_POST["rooms"]);
}
if (empty($_POST["type"])) {
$typeErr = "type of rooms required";
} else {
$type = test_input($_POST["type"]);
}
if (empty($_POST["name"])) {
$nameErr = "name required";
} else {
$name = test_input($_POST["name"]);
}
if (empty($_POST["address"])) {
$addressErr = "address required";
} else {
$address = test_input($_POST["address"]);
}
if (empty($_POST["zip"])) {
$zipErr = "zip required";
} else {
$zip = test_input($_POST["zip"]);
}
if (empty($_POST["telephone"])) {
$telephoneErr = "telephone required";
} else {
$telephone = test_input($_POST["telephone"]);
}
if (empty($_POST["email1"])) {
$email1Err = "email required";
} else {
$email1 = test_input($_POST["email1"]);
}
if (empty($_POST["email2"])) {
$email2Err = "email2 required";
} else {
$email2 = test_input($_POST["email2"]);
}
if (isset($_POST["email1"] != $_POST["email2"])) {
$email2Err = "please enter the same email address";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
This is failing you and isn't the right syntax for what you want to achieve:
if (isset($_POST["email1"] != $_POST["email2"]))
What you need to do is to first check if it is set then check if both are (not) equal to, but it's best to use !empty(), then check if it is not equal to:
if (!empty($_POST["email1"]) && !empty($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "Emails don't match. Please enter the same email address.";
}
}
Plus, make sure your form elements both have the right name attributes.
Also, a blank page can mean syntax errors.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
What you are doing is assigning by using a single equals to sign rather make it a double equals to sign, I mean ==
Try:
if (isset($_POST["email1"]) && isset($_POST["email2"])) {
if ($_POST["email1"] != $_POST["email2"]) {
$email2Err = "please enter the same email address";
}
}
I've created a test form that uses IF.. ELSE to validate data in a simple form. This works ok and any validation messages or errors are posted to the same page (userform.php) to inform the user of success or otherwise.
What I want to do now is take the user to a different page on successful completion of the form. Here's my code so far:
<?php
if (isset($_POST['email'], $_POST['password'])) {
$errors = array ();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST ['email'];
$password = $_POST ['password'];
if (empty ($firstname) || empty ($lastname) || empty ($email) || empty ($password)) {
$errors [] = "Please complete the form";
}
if (empty($email)) {
$errors [] = "You must enter an email address";
}
if (empty($password)) {
$errors [] = "You must enter a password";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
$errors[] = "Please enter a valid email address";
}
}
if (!empty ($errors)) {
foreach ($errors as $error) {
echo '<strong>', $error ,'</strong><br />';
$result = "userform.php";
}
} else {
$result = "confirm.php";
}
?>
<form action="<?php echo $result ?>" method="post">
The idea is that the users success or otherwise in completing the form changes the $result variable which is used in the form action. The above code doesn't work, so how would I do it?
Is it even possible?
instead of "form action=" at the bottom:
<?php
include($result);
?>
As I understand it you want it to work like so:
User fills form
User submits form
Form submission goes to userform.php
If all values validate, continue to confirm.php
If not, return to userform.php
If that's the case, I don't think you want to change the form action: that would require that the user re-submit the form. Instead, use a HTTP redirect to send them to confirm.php:
header("Location: confirm.php");
... or if you wanna be really by-the-book about it:
header("Status: 303 See Other");
header("Location: http://exampel.com/confirm.php"); // according to the protocol,
// `Location` headers should be full URLs
<?php
/* ... */
if (!empty ($errors)) {
foreach ($errors as $error) {
echo '<strong>', $error ,'</strong><br />';
}
?>
<form action="userform.php" method="post">
<?php
} else {
header("Location: confirm.php");
// if you need to pass additional information to confirm.php, use a query string:
// header("Location: confirm.php?var1=".$var1);
}
?>
The way you're doing it now, will redirect the user to confirm.php if they submit the form for a second time. You could change your code to this:
} else {
// $result = "confirm.php";
header("Location: confirm.php");
exit();
}
That way, if everything has been entered, the user will be redirected to confirm.php. But what do you do with the variables if everything is allright? They won't be taken to the new page.
} else {
$result = confirm.php;
foreach($_POST as $key => $val){
$input.="<input type='hidden' name='$key' value='$val' />";
}
$form = "<form method='post' name='confirm' action='confirm.php'>".$input."</form>";
$script = "<script type='text/javascript'>document.confirm.submit();</script>";
echo $form.$script;
}
empty ($errors)
will ALWAYS return empty. That's why you always get:
$result = 'confirm.php';
Check return values here
Also, I don't think you can do this easily. Instead, why don't you just create a check.php or whatever to check the variables/check for errors, etc. Then do whatever you want (redirect back to the form-filling page or proceeding to confirm.php page.
The whole idea is wrong. You have to fix 2 issues in your code.
1. A major one. Learn to properly indent nested code blocks!
It's impossible to read such an ugly mass with no indents.
2. A minor one.
I see no use of confirmation page here. What are you gonna do on that page? And from where you're going to get form values?
It seems you have to either use just simple Javascript code to show a confirmation or store entered data into session
And, I have to say, that show a confirmation page for simply a feedback form is quite uncommon practice.
So, I think you really need only one form action and only thing to ccare is properly filled form
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST ['email'];
$password = $_POST ['password'];
$errors = array();
if (empty ($firstname) || empty ($lastname) || empty ($email) || empty ($password)) {
$errors [] = "Please complete the form. All fields required.";
}
if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE){
$errors[] = "Please enter a valid email address";
}
if (!$errors) {
// do whatever you wish to this data
// and then redirect to whatever address again
// the current one is a default
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['fiestname'] = $form['lasttname'] = $form['email'] = $form['password'] = '';
}
include 'form.tpl.php';
?>
while in the form.tpl.php file you have your form fields, entered values and conditional output of error messages
<? if ($errors): ?>
<? foreach($errors as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form method="POST">
<input type="text" name="firstname" value=<?=$form['firstname']>
... and so on