how to eliminate space in forms in php - php

how can i prevent a form to be submitted when it only contains a space? for example a user presses the space bar on a field, the space will be considered as a character so the forms submits. how can i prevent that in php?

For PHP - Server-side validation (After the form is submitted)
A combination of trim() and empty() will return true if passed a string with only a space.
$a = ' ';
$a = trim($a);
if (empty($a)) print 'Empty!'; // Empty!
Sidenote: Under normal circumstances, it's always a good idea to trim() user-input.
For Javascript - Client-side validation (Before the form is submitted)
Use the onSubmit event to fire a validate function:
<form onSubmit="validate()">
<input type="text" id="myInput" />
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
function validate() {
myInput = document.getElementById('myInput');
if (myInput.value.match(/^s+$/) || myInput.value == '') {
alert('No Empty Values!');
return false;
}
}
</script>

Use trim() and then test against null values.
Mike B presents a good point. You could prevent the form from actually being submitted with Javascript. If you rely on PHP, the form will be submitted, but you could present the same form to the user with an error message.

HTML:
<form onsubmit="return validate(this);">
Javascript:
function validate(form) {
ok = true;
for (var i = 0, il = form.elements.length; i < il; ++i) {
form.elements[i].value = form.elements[i].value
.replace(/^\s\s*/, '')
.replace(/\s\s*$/, '');
ok &= !!form.elements[i].value;
}
if (!ok) alert("Oh hey - type something in these boxes, k?");
return ok;
}
PHP:
$myVar = trim($_POST['myFormVariable']);
if (!$myVar) {
echo "Oh hey, you should type something.";
} else {
doStuff();
}

Once your forms get more complex Jquery has a wonderful plugin for this called validate that provides extensive form validation.
+1 to Plan B. Always validate the same input again in php as there is nothing stopping a user from just creating his own form and submitting it to your page.

Related

Determine if empty $_POST submitted

I have a form containing tabular data, with each row having a checkbox with the same name so that it gets passed via POST as an array to a PHP page. Everything work fine, but I have an issue relating to when none of the items on the page are selected - this is a special case that I need to handle in a specific way, but I am trying to figure out how to determine the best way to tell when this condition occurs, as when it does the $_POST array is completely empty.
Any strategies to help in determining when an empty set of data has been POSTed to a page in PHP?
Use the empty function
if( empty($_POST) ) {
//do empty $_POST stuff here
}
Add a hidden input field to the page with a known value. This field will always be passed in with the POST data, therefore you will know that the user landed via form submission rather than direct URL. It's as simple as:-
<input type='hidden' name='posted' value='true'>
You can accomplish this a few different ways.
//Method 1
if($_POST) {
//Do Stuff
}
//Method 2
if(!empty($_POST)) {
//Do Stuff
}
//Method 3 - For detecting if a form was submitted
<input type="submit" name="submit" />
if(sizeof($_POST)>1) {
//Do Stuff
}
Method 2 will fail if your value is 0, for a checkbox you need not worry though.
Method 3 relies on you giving your submit button a name, so it is at least submitted when nothing is checked. Then you can see if sizeof() returns more than 1 to see if anything was checked.
DEMO: http://wecodesign.com/demos/stackoverflow-7424062.php
I think you've answered your own question. If the $_POST array is empty then there are no checked checkboxes.
<form>
<input type="text" name="user" value="" />
<input type="submit" name="post" value="Save" />
</form>
//php
if (isset($_POST['post']))
{
//code here
}
if ( !empty( $_POST["field"] ) ) {
// Field sent
} else {
// Field empty
}
(count($_POST) == 0) //returns boolean
or do you mean when the form is posted but no information is entered?
Post data is available when a form is submitted. Given the following:
if($_POST)
{
// Bar
}
// Foo
If the form is not submitted Foo will be performed.
If the form is submitted Bar will be performed and then Foo.
Given the following:
if ($_POST)
{
// Bar
}
else
{
// Foo
}
If the form is not submitted Foo will be performed.
If the form is submitted Bar will be performed.
As for your other question, checking for empty or appropriate data is basic server-side form validation. If you use a library that can be as simple as:
if ($_POST)
{
$form_helper = new FormHelper();
$form_helper->validate($_POST["email"], "email");
$form_helper->validate($_POST["password"], "password");
if (! $form_helper->notifications())
{
// Bar
}
}
For your specific case (and without a library) it might be:
if ($_POST)
{
if (empty($_POST["checklist"])
{
// Delete all entries.
}
else
{
// Do something else.
}
// Foo
}
This will check if any form values have been entered - assuming default input value = ''
$post = array_filter($_POST,'strlen'); //filter all empty values
//if html input submit button has NO name value
if (sizeof($post)):
//Do stuff
endif;
// OR if html input submit button HAS a name value
if (sizeof($post) > 1):
//Do stuff
endif;
You could use a callback function if exact filtering was required
$post = array_filter($_POST,function ($k){ return $k != '' || $k != 'my default value' || *some other condition etc etc* ; });

How to prevent a "space" from searching MySQL database?

Currently, when someone just hits the space key and hits enter it will go to the next page but not search anything - I want to prevent the search altogether. What is the best way to accomplish this? I don't want to prevent spaces from being used (ie: How do I fix this?) - I just dont want spaces themselves to allow a search.
Wrap your query variable in an empty condition:
if(!empty(trim($_POST['searchterm']))
{
// do search
}
Use JavaScript and trim leading spaces in the submit (onsubmit) event handler:
var searchField = document.getElementById('search'); // or whatever the id of the field is
if(searchField.value.replace(/^\s+/, '').length === 0) {
return false; // or evt.preventDefault().
}
It should be okay to rely on client-side validation here because if the user wants to fool the search engine then they won't mind being brought to a blank page. If there's an actual server-side problem in allowing this, then perform the same check server-side:
if(!isset($_REQUEST['search']) || !trim($_REQUEST['search'])) {
// Don't perform the search
}
In addition to #AlienWebguy answer you can use JavaScript to do client side validation in order to stop the page from even getting to the back end. Its definitely a good practice to do the validation on the client side AND server side.
Live Demo
form.onsubmit = function(){
if(input.value.replace(/^\s/,"").length === 0){
return false;
}
}
Just take the string, trim the initial and final spaces and check the length; if length is 0, don't submit the form.
If you are procecssing it with php on the backend you can just use trim($input), but for a better user experince use javascript. Set a form validator so it won't submit unless there is something other than whitespace.
<form onsubmit="return verify()">
<input id="foo" name="foo" />
<input type="submit" />c
</form>
<script type="text/javascript">
function verify() {
if (document.getElementById("foo").value.match(/[^\s]/) == null) {
alert('only whitespace');
return false;
} else {
alert('found substance');
return true;
}
}
</script>

How can I check a input field exists in the form when I submit it to the server?

How can I check a input field exists in the form when I submit it to the server?
For instance, I want to check whether a check box named 'mem_follow' exists or not in the form.
Or do I have to use javascript (jquery)?
I'm guessing you need to check on the server side after the form is submitted. If that's the case, you can check like so...
<?php
if (isset($_POST['mem_follow']))
{
// Work your server side magic here
} else {
// The field was not present, so react accordingly
}
?>
Hope this helps!
It'd HAVE to be Javascript. PHP can't reach out from the server into the browser's guts and check for you. It could only check if the fieldname is present in the submitted data.
In jquery it's trivial:
if ($('input[name="nameoffield"]')) { ... field exists ... }
Of course, this raises the question... why do you need to know if a field exists or not? Presumably you're the one who's built the form. You should know already if the field exists or not.
In the following script the form will not submit unless the checkbox is ticked. And If you do try, the hidden div with an error message is shown, to let you know why.
<form action="test.php" method="post" id="myform">
<input type="checkbox" name="checkbox" id="checkbox" value="YES" />
<input type="submit" name="submit" value="submit" />
</form>
<div id="error_message_div" style="display:none">You must tick the checkbox</div>
<script>
$('#myform').submit(function() {
if($('#checkbox').attr('checked')) {
return true;
} else {
$("#error_message_div").show();
return false;
}
});
</script>
Cheers
Matt
you can do this in two way:
By Server Side: In php
<?php
if (isset($_POST['mem_follow'])
{
// Work your server side magic here
} else {
// The field was not present, so react accordingly
}
?>
By Client side: In Jquery
$('#submit_button').click(function() {
if ($('input[name="box_name"]')) {
if($('input[name="box_name"]').attr('checked')) {
return true;
} else {
return false;
}
}
});
You can use jQuery and do something like this:
$('#myForm').submit(function (e) {
if($(this).children(':checkbox[name=mem_follow]').length > 0)
//exists
else
//doesn't exist
});
Or use php and check if there is any variable named 'mem_follow': (this is for POST, although it doesn't matter if it's GET or POST)
if(isset($_POST['mem_follow']))
//exists
else
//doesn't exist
You can try this code in the form submit event handler
if($("input[name=mem_follow]").length > 0){
//It exists
}
The other answers here are correct: you'd have to do that on the client side. In the case of a checkbox input field, if the box is not checked there is no guarantee the browser will include a POST parameter for that field.
For example, if you submit this form without checking the checkbox:
<form action="test.php" method="post">
<input type="checkbox" name="checkbox" value="YES" />
<input type="submit" name="submit" value="submit" />
</form>
only the submit=submit parameter will be submitted.
So, no, you cannot guarantee that a given checkbox exists in a form on the server side.
well for all elements try this
number = document.form_name.elements.length;
else for a specific name of input use this
number = document.form_name.getElementsBYName('Name of Input').length;
Thats it
enjoy
I suggest you to use Jquery
$.fn.Exists = function() {
return $(this).length>0;
}
if ($("here are your selector to check").Exists()) {
...
}
Simple and useful!
And you can use this Exists method everywhere))))
You can use javascript (or jQuery) to do that :
<script>
$('#myform').submit(function() {
if($('#yourFieldId').val()=='') {
alert('the field ' + $('#yourformField').name() + ' is empty !');
return false;
} else {
return true;
}
});
</script>
you can do this for all your fields one by one, or by putting all conditions in the if statement.

Code that checks for required text in textboxes upon submit

how can I check if the user filled some textboxes upon submit? My textboxes have different id and name.
If the user did not fill the required like password the form is not continued.
Thank you.
You can do this using JavaScript or within the script itself.
If using javascript, you simply check the form fields against your requirements before allowing the form to submit. However, you may still need to implement this in the script in case ofr some reason they have javascript turned off.
Basically, in the script, you check the values of the form when they submit:
if($_GET['field_name']) !== 'the value I expect') {
// show the form again with errors
}
// continue
Hope that helps.
Try the below. Naturally you can tweak the form and id's and such, but the basic principle should work. also shown here: http://jsfiddle.net/j3nSB/2/
<form>
<input type="text" id="username" value=""/>
<input type="password" id="password" value="" />
<input type="submit" id="submitButt" value="Go" />
</form>
document.getElementById("submitButt").onclick = function () {
if(document.getElementById("username").value.length == 0 |document.getElementById("password").value.length == 0) {
return false;
}
}
Assuming you have one form, here is the most simple/generic way I can think of, using plain JavaScript.
<script type="text/javascript">
var arrRequiredFields = [ "txtPassword", "txtEmail" ];
window.onload = function() {
document.forms[0].onsubmit = function() {
for (var i = 0; i < arrRequiredFields.length; i++) {
var field = document.forms[0].elements[arrRequiredFields[i]];
if (field && field.value.length == 0) {
alert("Missing required value");
field.focus();
return false;
}
}
return true;
};
};
</script>
Just put the names (not ID) of the required elements, put the code in your page and you're all set.
Live test case: http://jsfiddle.net/kf7pL/
use this:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Its very easy to use, and you can just add a class of 'required' to each required input field.
its as easy as $('#form').validate();
It also supports things like integer and date. Highly recommend it to anyone

losing variables from javascript array when passing to php

I'm trying to implement a page with a choice of user's preferences in an HTML form where if the checkbox ALL is selected then all sub-checkbox base1, base2 and base3 are checked automatically, and if any of sub-checkboxes is un-selected then the checkbox ALL must be unchecked. I used a javascript function which works but when I submit the form only the last variable in the array of checkboxes is sent.
<SCRIPT LANGUAGE="JavaScript">
function checkChoice(field, i) {
if (i == 0) { // "All" checkbox selected.
if(field[0].checked==true) {
for (i = 1; i < field.length; i++)
field[i].checked = true;
}
}
else {
if (field[i].checked == false) {
field[0].checked = false;
}
}
}
<form name="form" method = "POST" action="preferences.php">
<input type=checkbox name=classes1 value="allbases" onclick="checkChoice(document.form.classes1, 0)">All bases
</td><td>
<input type=checkbox name=classes1 value="base1" onclick="checkChoice(document.form.classes1, 1)">Base1
<br>
<input type=checkbox name=classes1 value="base2" onclick="checkChoice(document.form.classes1, 2)">Base2
<br>
<input type=checkbox name=classes1 value="base3" onclick="checkChoice(document.form.classes1, 3)">Base3
<input type="submit" value="Set preferences" >
If I call the checkboxes'names in "classes1[]" all the values are submited but the javascript function doesn't work anymore. Is there a way of fixing this?
Thanks for any help.
For an alternative of checkChoice: check this SO question and the jsfiddle I presented there.
[edit] concerning your comment: a bit of extra thinking would have brought you to this solution
All of the values actually ARE submitted but PHP will overwrite $_POST['classes1'] each time until you are just left with the last value. If however you add '[]' to your input names then they are added to an array.
Since the latter causes a problem with javascript, can you not just either
a) iterate all of the form elements from the form.elements array,
or b) give each input a unique id and use document.getElementById() to find it?

Categories