How do i keep the information a user has entered in a form in a case where s/he has made an error in the form so that s/he does not have to make the entries once again?
I would also like to indicate the errors made by highlighting the texboxes with the errors with a red color
There is no "magical" solution : when the form has been submitted with an error, you have to :
redisplay the form,
filling out the fields with what the used did input (what you received in $_GET or $_POST), putting those data in the right attributes
i.e. value for <input>
or as content for <textarea>
or setting the selected attribute for <select>
and, not forgetting to escape the data, with htmlspecialchars, to prevent HTML injections
For the indication of errors made, a solution is to add a CSS class to the form elements on which you have detected an error.
Adding something like class="error" for <input>s on which there's been an error, and having the .error class properly defined in your CSS file.
Generally the idea is to use:
<input type="text" name="field_1" id="field_1" class="<?= ($errors['field_1'] ? 'error':'') ?>" value="<?= #$_POST['field_1'] ?>" />
This fills the value of the text box with whatever the user inputed and gives you something to style if your script to handle this form deems this value to be invalid.
e.g.
if(empty($_POST['field_1']))
$errors['field_1'] = 'Cannot be blank';
Related
I want to display warning messages in html. This code shows two text boxes named "company" and "name". con.php connects to the database and inserts the information. But if I enter nothing, then the values are still getting stored in the database as null. I want user to know that he shouldn't leave the fields blank by displaying some messages and also a warning should appear if the given company already exists in the database. How do I implement that?
<html>
<head>
<title>store in a database</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h2>company Store</h2>
<form name="form1" method="post" action="con.php">
<p>company:<input type="text" name="company">
<br/>
<br/>
<br/>
Name: <input type="text" name="name" size="40">
<br/>
<br/>
<br/>
<input type="submit" value="Save">
<input type="button" onclick="window.close()" value="cancel">
</form>
</body>
While an alert message cannot be produced without JavaScript, you could take advantage of HTML5's placeholder attribute to inform the user of this message:
<input type="text" placeholder="You must enter something in this field"! name="whatever" id="whatever" />
And couple this with JavaScript:
var inputElem = document.getElementById('whatever');
var form = document.getElementsByTagName('form')[0];
form.onsubmit = function(){
if (inputElem.value = '' || inputElem.value.length < 1){
alert('You must enter some actual information');
return false;
}
};
However JavaScript can be edited by the users, via Firebug, Web Inspector, Dragonfly...or by simply creating a new html file and submitting the form to the same source from the action attribute of the form element. Therefore your form-handling script must be sanitised and checked on the server as well as the client; client-side checking is a convenience to the user (to prevent unnecessary page-reloads, submissions and so on), it is not a security feature, and should not be used, or mistaken, as such.
Best way is using Ajax if you want to do it at the same page. You need to read some tutorials on it. It's not that easy to explian here.
If reloading or redirecting to other page is ok for you, you should compare the submitted form value with the values in the database in a PHP script which is redirected from form submission (action url). If values doesn't match and not empty, store the values to database and redirect to a page like the list of companies or "company successfully created" message page. If values match with an old record or empty, redirect back to the same form page with a flag (something like form.php?error=1 etc.) and show the proper error message.
Also you can use JavaScript for immediate alerts. But you should always do the same checks at PHP side since JavaScript can be disabled in browsers.
In con.php you should do your data validation and return the markup (or redirect to page describing the error).
So, check for empty fields, and if the exists redirect the user to a page saying the fields can not be empty (and probably allow them to enter new values).
If the data entered is ok, check the database for duplicates and if they exist, redirect the user to a page saying that the company already exists (and again probably allow the user to correct the data).
You can not do it only with HTML.
You need to add a form validation (to prevent empty strings), HTML5 form validation can do that for you (check http://www.broken-links.com/2011/03/28/html5-form-validation/), but not all browser support it, so you will need to use JavaScript to validate the form.
There are JavaScript libraries that will take an old browser and make it behave like a browser that support HTML5 (check http://www.matiasmancini.com.ar/jquery-plugin-ajax-form-validation-html5.html).
You will also need to retrieve the companies already in your database and check them against the user input and alert him if needed.
On top of that you will need to validate the data in your PHP before inserting it to the database (check for empty string for example).
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 :-)
After filling the form when submit, accidentally due to some filling error ,the form is not submit and return to back,in this condition the value of all text box is blank. i want to stable value of all fields in this condition . I'm using php with smarty framework. Please reply with solution as soon as possible.
Thanks.
If the form is submitted to the page that contains it then you will have access to the submitted values, and can use them to populate your form. For example, if you are submitting the form via POST:
<input name="something" value="<?=$_POST['something']?>" />
If you are submitting the form to a different script, you could send the values back to the page with the form as URL parameters, or you could use temporary session variables, and unset them when the input passes whatever validation you are using:
$_SESSION["temp_something"] = $_POST["something"]; //In form processing script
Then in your form:
<input name="something" value="<?=$_SESSION['temp_something']?>" /> <!--In form-->
You can fill the form fields, on the second round, by filling the content inside the value attributes of html tags, like so:
<input type="text" value="<?php echo $_REQUEST['test']; ?>" name="test">
Pay attention: this is a fast and simple solution. It gives you an idea. In good web programming practice you should sanitize the form data received by client in order to avoid security issues.
is there a way to create custom post variables when a user presses submit, like this:
$_POST['var'] = 'hi';
In order to set post values on the page with the form you should use hidden input tags.
i.e.
<input type="hidden" name="var" value="hi" />
It will be invisible and your receiving script will see that key/value passed along.
Variables POSTed by the browser to your PHP script will only correspond to the fields of the form that was used in the browser -- which means you have to put your custom data in that form.
If you don't want them displayed, you can use a hidden input field :
<input type="hidden" name="var" value="hi" />
But note that the data will still be sent by the browser -- which means you have to escape/filter/protect it, like any other value that comes from the user ; and it cannot be trusted : anyone can pretty easily modify the value of that form field, even if it's not visible.
while $_POST variable is an array, you can also define var like this
$_POST['var'] = 'hi';
it is same like hidden field. :)
I've written a simple entry form that compiles information onto a database, and I'm having trouble with my required fields...
I use a form to process the data via post method if the user neglects to fill in a required field I would like to bring him back to the original form with his/her previous fields entered.
How to I pass info back into an input label? Is there an easy way to do this without any crazy scripts? I started with sessions but I realized I have no clue how to put the stored info from the session back into the input field so the user doesnt have to retype all of their info... Also would a cookie be better for this over session?
Thanks guys,
Arthur
When you post a form, all those variables are submitted into a global array named $_POST['input_name'] and available on the page posted to. A lot of times what I like to do if I'm doing it fairly quickly, is just make the value of those input fields equal the same as what would be posting.
For example lets say we have a desired username field but the form didn't validate for some reason and posted back to itself; we don't want them to have to enter it again:
<input type="text" name="username" value="<?php print $_POST['username']; ?>" />
Of course when they first load the page, the value will be empty so there is nothing there, but if for some reason it posts back, that "username" field will already contain entered information.
Even better is java script validation, as the form doesn't have to post back, but this will do the job just fine!
Since the user posts all your data to you, these values are also available in your scripts. So you can use them very easily in the case of text-fields, but a bit more work is required for select options, checkboxes and radio buttons:
<input id="myid" name="myid" type="text"
<?php echo !empty($_POST['myid'] ? "value=\"{$_POST['myid']}\"" ?> />
For radio buttons, select options and checkboxes you instead have to check the value to see if it corresponds with the entry you are currently outputting and print selected="selected".
When it comes to validation you can also have a JavaScript validation to give feedback sooner to the user about possible failures. Just remember to have the same validation on the server side in case someone doesn't have JavaScript enabled or submits it using JavaScript, thus bypassing your client side validation.
Not sure if this is the best way, but you could redirect to a "reload" page and use the values from POST or GET to reinput the existing fields. So first validate, the fields that are required and if any are missing, redirect to this page. Then the POST or GET will have all of the values the user filled in (and the missing required fields will already be blank) so you just loop through and load up the supplied info. Additionally, if they supplied incorrect info you could manually clear it and this will also allow you to mark the missing required fields.
Another option is put your validation in JS so you know the data is good before you submit. However, I'm not sure if there are security concerns with that or not.
I check to see if the post value has been set otherwise you can show a default value, then use a bit of jQuery to remove it when the input has focus
<input type="text" name="first_name" id="first_name" value="<?php if(isset($_POST['myid'])) { echo $_POST['myid'] } else { echo "Your Name" ?>"></input>
Here's the jQuery which will remove the default Your Name when the textbox has focus.
$(document).ready(
function(){
$.fn.clearDefault = function() {
return this.focus(function() {
if( this.value == this.defaultValue ) {
this.value = "";
}
}).blur(function() {
if( !this.value.length ) {
this.value = this.defaultValue;
}
});
};
// clear default textbox entries
$("#first_name"). clearDefault();
}
);
jQuery Validation Plug-in
<input type="text" name="username" value="<?php isset($_POST['username']) ? echo $_POST['username'] : null; ?>" />
will work fine