PHP form validation error messages placement - php

Is it possible to place error messages resulted from form validation inside the form, using PHP/XHTML/CSS only?

You can put error messages anywhere on the site you wanted. It all depends on where in your scripts you place your code to emit it.

One strategy I've seen used a lot in PHP Frameworks when AJAXy submissions are disabled is to have a field to display the error on the page, and then actually populate that field with the data if the page comes back with an error.
Such as:
<label for="field">Label"><input name="field" type="text" />
<?php if($_POST['errors_field']) echo '<p class="error">'.$errors['field'].'</p>'; ?>
This strategy would only show the <p> tag when the page input box has an error. This method of course involves returning a populated array of all errors to the page when it fails validation.

I would make 2 pages one with the form like this. We will call it form.php. Make sure your form method is "post", and you have named your inputs. create a div that will be used for error callback($error). You can place the Error var anywhere you want not just in the form.
<form method="post">
<input type="text" name="text">
<div><?php echo $error ?></div>
<input type="submit" name="submit">
</form>
Next Make another php page like this and include the form.php page at the bottom. set error as empty string first. See if the button is clicked(isset). If the field is equal to a empty string set the error($error). if no error Process the form. Hope this helps.
<?php
$error = '';
if(isset($_POST['submit'])){
if($_POST['text'] == ''){
$error = "Here is your Error inside the form.";
} else {//"Sanitize and Process the Form";
}}
include 'form.php';
?>

Related

Basic form in Wordpress template

I need to simply get a search term from a form into a variable. I have set up a basic form within a template file, that template file is then linked to a page within Wordpress admin. The problem I am getting is that the form doesn't submit so I am unable to use the variable. If I remove get_header(); from the template then the form will submit but obviously it break wordpress stuff.
Here is my form:
<form action="<?php the_permalink(); ?>" method="post" autocomplete="off" >
<label>
<input placeholder="Search…" name="qcsearch" type="text">
</label>
<input type="submit" name="submit" value="Submit">
</ul>
</form>
I have tried leaving out the action, using the template name which is qccerts.php and using $_SERVER['PHP_SELF']
Here is then what I am trying to do with the output:
if(isset($_POST['submit'])){
$searchterm = $_POST["qcsearch"];
}else{
$searchterm = '';
}
Its basically a simple search which tells the users if there is a file by the name they search. So I need to populate $searchterm so I can use it later down the page.
Any help appreciated.
It's difficult to determine what your exact problem is without a reproducible scenario. For example, without seeing your problem, I'm not sure whether the form is really not submitted at all, or submitted, but you did not see it being executed, or there is some Javascript which prevents your form from submitting. There is a possibility that the form is submitted to the wrong action as well.
However, if you intend to keep your search term accross the pages, you could add it into session. Let's imagine these functions:
function storeSearchTerm($searchTerm) {
$_SESSION["searchterm"] = $searchTerm;
}
function getSearchTerm() {
return isset($_SESSION["searchterm"]) ? $_SESSION["searchterm"] : "";
}
By calling these functions you can manage the search term, initializing it via storeSearchTerm($_POST["qcsearch"]) or something.
As about your actual form, if it does not work, then you can submit the form in Javascript, such as
document.getElementById("myForm").submit();
and make sure that this is triggered either via an onclick attribute, or a click event listener on the button created via addEventListener.
EDIT
It turns out that a class name was not well formed (case-sensitivity issue).

How to display validation error near textbox

I have this form in index.php
<form action="result.php" method="post">
<input type="text" name="word" class="tbox">
<input type="submit" name="submit" value="Generate Now">
</form>
In result.php i am checking whether the input matches all validation condition and generating the output. Now, if it doesnt match, i ve to throw an error near my text box. Is that possible through php?
Using PHP, you may try like below
<input type="text" name="word" class="tbox"> <?php if(isset($_POST['word']) && $_POST['word'] == ''){ echo 'YOUR ERROR MESSAGE'; } ?>
a few things, one you can just post against the page itself not great to have DB functions and the like in user reachable areas so check out includes and use them to reference the single page.
Then make a simple variable and slide it into your form as such
<? echo $error ?>
and set error to something via the php script imported from result.php, or you may want to learn about sessions and get variables if combining the files via include isn't on the table.
Once its working then say make a div box as such
<? if (isset($error)){?><div class="errorbox"><? echo $error?></div><? }?>

Required field display error message on form

I have a form that I need to have required fields filled out. I know to use the code below to verify if the field is blank:
<?php
if (!empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>
My question is, how do I get the error message to display on the form page, saving all the data already entered in the form. Example: I fill out all 15 fields on the form, excluding the required field. When I hit the submit button, if the required field is empty, I want to stay on that form page, without losing any of the info I put into the fields, and I want to display a message next to the required field box, saying "This is a required field.
I am not sure on the code to do that, or where to put it. On the form, or on the script that executes the form?
use client side javascript validation first, then php server side validation.
Why you use !empty you can use empty for best result like
<?php
if (empty($_POST['client_name'])) {
echo '<p style="color:red;">'"Client Name is required!"'</p>';
}
?>
Actually you should be first set HTML5 validation like
<input type="text" name="abc" required="">
You can set custom error message for required field like
<input type="text" name="abc" required="" oninvalid="this.setCustomValidity('Please Select This')">
Then you can use JS or jQuery validation and then user Server side Validation like PHP or ASP or others.
Thanks.
Without knowing the structure of your pages, it's hard to give an exact answer, but here's a general process flow that should help:
Form is submitted to processor
Processor validates inputs
if inputs are good, processor redirects to next page
if inputs are not good, processor should send error text and form data back to the routine that builds/displays the form.
IMHO, the processor should not echo anything. All display should be handled by the script that builds the form.
Without coding it for you, that's the best answer I can give :-)

Same page processing

How can process a form on the same page vs using a separate process page. Right now for signups, comment submissions, etc I use a second page that verifies data and then submits and routes back to home.php. How can I make it so that on submit, the page itself verifies rather than using a second page.
You can tell the form to submit to the PHP's self, then check the $_POST variables for form processing. This method is very good for error checking as you can set an error and then have the form reload with any information the user's previously submitted still in tact (i.e. they don't lose their submission).
When the "submit" button is clicked, it will POST the information to the same page, running the PHP code at the top. If an error occurs (based on your checks), the form will reload for the user with the errors displayed and any information the user supplied still in the fields. If an error doesn't occur, you will display a confirmation page instead of the form.
<?php
//Form submitted
if(isset($_POST['submit'])) {
//Error checking
if(!$_POST['yourname']) {
$error['yourname'] = "<p>Please supply your name.</p>\n";
}
if(!$_POST['address']) {
$error['address'] = "<p>Please supply your address.</p>\n";
}
//No errors, process
if(!is_array($error)) {
//Process your form
//Display confirmation page
echo "<p>Thank you for your submission.</p>\n";
//Require or include any page footer you might have
//here as well so the style of your page isn't broken.
//Then exit the script.
exit;
}
}
?>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<?=$error['yourname']?>
<p><label for="yourname">Your Name:</label><input type="text" id="yourname" name="yourname" value="<?=($_POST['yourname'] ? htmlentities($_POST['yourname']) : '')?>" /></p>
<?=$error['address']?>
<p><label for="address">Your Address:</label><input type="text" id="address" name="address" value="<?=($_POST['address'] ? htmlentities($_POST['address']) : '')?>" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
The easiest construction is to detect whether the $_POST array is not empty
if(isset($_POST['myVarInTheForm'])) {
// Process the form
}
// do the regular job
you can check if it was POST request inside the page's code and then check the data. If it was GET request - just show the form.
But please remember that is is a good practice to show successfull form submission results on a different page served through GET request, i.e. any successfull form POST should be answered with redirect to the success page.
You could of course explore looking into AJAX requests, where you would make an asynchronous call to your handler script, and then update then update the sending page with a success message. This gives the impression of "Same page processing" i.e. The page doesn't have to refresh.
It really depends on the effect you are trying to achieve however.
#Michael Irigoyen: It works fine, but on first rn/load, it shows:
"Notice: Undefined variable: error in C:\xampp\htdocs\same_page.php on line 28"
How to handle this notice?
Got it now:
"Used isset, # etc. to supress errors..."
"Works like a charm!!!"
"Now i'll try it on my code..."
I have saved a thank you message and refreshed using session variables.
if(!is_array($error)){
$_SESSION['message'] = 'Thank You!';
header('Location: yourpage.php');
exit();
}
and then use this in the top of the form:
if(isset($_SESSION['message'])){
echo $_SESSION['message'];
unset($_SESSION['message'];
}
This should refresh the page and show the message and then if they refresh the page the session variable is empty so the thank you won't show. This is called a flash message.

PHP Form Processor Error Passback

I have a basic PHP form page that contains quite a large amount of data that will be saved into about 4-5 different tables in MySql once it is all done. Since constructing this save routine will take a bit of PHP I'm looking to have the POST action to not point at PHP_SELF and instead a separate PHP file for processing.
Where all general data such as phone numbers, email, zip codes, etc. will be validated prior to the submit is passed to the processor script, if an error is returned by the processor...
What is the best practice way to point back to the original form page (HTTP_REFERER) while maintaining data input?
Form page:
<form action="processor.php" action="post">
<!-- lots of fields -->
<input type="submit" id="submitButton" name="Save" value="Save" />
</form>
Processor page:
<?php
if ( isset($_POST['date']) && ($_SERVER['HTTP_REFERER'] == "form.php") )
{
$errors = false;
//attempt to put data in database
if ( $errors )
{
//Pass back to the form.php page with error message and all data intact
}
}
?>
I have come across this problem before, how we solved this was to put all the fields into a session, then redirect back to form.php using header("Location: form.php");
When the data was posted to the form, we stored the $_REQUEST into a $_SESSION['post']; if the validation failed, we sent it back to the form, populated the fields and unset the session.
So for example
$_SESSION['post']['field_a'] = $_REQUEST['field_a'];
$_SESSION['post']['field_b'] = $_REQUEST['field_b'];
With some fancy naming conventions you can just loop this to make it easy.
Then on the Form page, we just checked to see if there was some data, or just echo the data regardless.
$str_field_a = #$_SESSION['post']['field_a'];
...
<input name="field_a" value="<?php echo $str_field_a; ?>" />
...
unset($_SESSION['post']);
This is probably a messy way of doing this, but it has proven effective for our purposes. Just thought I'd share.
I would send a post back to form.php containing errors and values. I use the same method in my personal project.
if ( $errors ) {
?><form action="form.php" method="post" name="error">
<input type="hidden" name="errcode" value="<?php echo $errorcodes; /*or whatever message*/ ?>" />
<input type="hidden" name="anotherdata" value="anothervalue" />
<?php /*you can add all post datas here as hidden field*/ ?>
</form>
<script type="text/javascript">document.error.submit();</script><?php
}
And this is similar to my form.php
//first I set default blank variables for form
$formvalue="";
$formnumericvalue="";
//i set them, yay!
//if I get values from post.php, I update the values
if (isset($_POST['iserror'])) { //you can either echo a error message or update current data here, I'm showing this for both
$formvalue=$_POST['formvalue'];//don't forget to validate these!
$formnumericvalue=$_POST['formnumericvalue']; //don't forget to validate these!
}
//I also do this method for edit forms
//and finally I show the form
?>
<form name="form" method="post" action="post.php">
<input type="text" name="formvalue" value="<?php echo $formvalue; ?>" />
</form>
I think you can do that using an array of error.
Set error flag false (if error occurs then set it true and so not store in database).
Check element 1, if error then store it in array $error['name'] = 'value'
Similarly check all elements, and store using same procedure.
In the end if error flag is set to false do not store in database and (if on the same page, you will be able to access the array on form where you want to display error message. )
if(isset($error['elementname'])) echo $error['elementname'];
below the page.
However, the best approach is to use an Object Oriented approach.
[UPDATE]
storing php objects on html form element and passing php objects through GET method?
how to send redirect page pass variables as post variables from a php script
Also I guess, storing the whole object in SESSION would not be a bad approach

Categories