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

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>

Related

javascript if checkbox is checked, href to ?page2, if at ?page2: keep cb checked, when unchecked, href to ?page1

Im totally new to javascript and i have no clue how to get this to work... I modified the code a little, but note that line 6 makes no sense. That is the main reason for this post.
<script>
function checkReloading() {
if (window.location.href.split=="?showpastdate") {
document.getElementById("showpastdate").checked=true;
} else {
document.getElementById("showpastdate").checked=false;
}
}
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.replace("?showpastdate");
} else {
window.location.replace("");
}
}
window.onload=checkReloading;
</script>
Ok i think this is pretty readable.
First of all window.location.href.split doesn't work because I have to give in the full path. But how can I make this dynamic, so it can be used on more websites? Everywhere I see: window.location.protocol + "//" + window.location.host + "/" + window.location.pathname; but how do I implement this line of code for dynamic webpages? Can someone give me an example?
What I want to achieve with this code is:
When showpastdate is checked, href to ?showpastdate, when at ?showpastdate stay checked so i can use php $_GET on ?showpastdate. This works (when i use static full url). But than...
How do I have to modify this code so that the checkbox remains checked at ?showpastdate untill clicked again, than url goes back to original .php state or other GET var?
Sorry for asking for code writing, but I bet some of u can write this simple lines in 2 minutes while I'm surfing around for 8 hours. Not about to learn javascript, but this really would be a nice option for my program to toggle item showing past date ON/OFF, nicer than having 2 checkboxes, 1 for ON and 1 for OFF :x EDIT: + a submit button #(O _o)#
Thanx in advance.
.split() is a function you can execute on a string object, to split it up in pieces, depending on a parameter provided:
"abcdefg|hijklmnop|qrstuvw".split('|')
would result in a array like this:
["abcdefg","hijklmnop","qrstuvw"]
Now, I am guessing you have added a "?showpastdate" parameter to the url, to change a checkbox's "checked" status.
The easiest way to do that would be:
document.getElementById("showpastdate").checked = (~window.location.href.indexOf("?showpastdate"))
This part: window.location.href.indexOf("?showpastdate") Searches the href for
"?showpastdate"
If the string has been found, it will return a index. if not, it will return -1.
The squiggly in front of it is to convert the -1 or 0 (or higher) to a true / false.
I'm not quite sure what the toggleAutoRefresh() is supposed to do, though
Edit 1
Ah, for the toggleAutoRefresh(), just add this:
if (cb.checked) {
window.location.href.replace("?showpastdate","");
}
instead of that if-else block you have there.
The .replace() function works on a string the same way .split() does. It takes 2 arguments: What to look for, and what to replace it with.
So, for example:
var someString = "words and stuff"
var result = someString.replace(" ","_");
//result will be "words_and_stuff"
Edit 2
These functions should work:
function checkReloading() {
document.getElementById("showpastdate").checked = (~window.location.href.indexOf("?showpastdate"))
}
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.href.replace("?showpastdate","");
}else{
window.location.href += "?showpastdate";
}
}
Where are you calling toggleAutoRefresh() from?
Edit 3
What I can conclude from your last comment, is that you want to do something like this:
// If a checkbox named "cb" is checked, and the url contains "?showpastedate"
if ((cb.checked) && ~window.location.href.indexOf("?showpastdate")) {
//Uncheck the checkbox and remove the "?showpastedate" from the url
document.getElementById("showpastdate").checked = false;
window.location.href.replace("?showpastdate","");
} else {
// Else, check the checkbox and add the "?showpastedate" to the url
document.getElementById("showpastdate").checked = true;
window.location.href += "?showpastdate";
}
Note the use of the "~" in front of the indexOf.
If string.indexOf("text") finds "text" at the beginning of a string, like it would in "tekstbooks bla bla bla", it returns 0. First index, starting count at 0.
This zero is interpreted as a false, when implicitly casting it to a boolean. So, if the indexOf were to find a result at the first index, it should (In this situation) return true to indicate a string has been found. That's why we apply the Bitwise NOT ~ to the results of indexOf. -1, indexOf's "Not found" value returns false, and all other results return true.
URL Change Event - JavaScript
http://help.dottoro.com/ljgggdjt.php
I think you could also use the onchange() javascript event.
I'll explain a little bit more.
I have a JQuery datatable, and through CSS I have different <tr classes>. Depending on the information stored in the database, these <tr> get a different class, thus a different color in the datatable.
Now for one <tr class> I'd like to give the user the option to hide/show. I was thinking to do this with a checkbox, and the javascript would parse an url when checked, and remove it when unchecked again. This URL can be used for php to run different queries, if $_GET['parsedurl']: query to show all tables, elseif $_GET['empty']: query for not showing that 1 information.
But this is the worst way to do it. I need to find something to toggle the display: none on or off of the table class, since this is working client-side.
So Im now thinking to keep the parsing of the javascript in an URL and depending on the URL, I run the .php GET to echo out <tr style: display: none> or just simply <tr>
Therefore I need some javascript which does this:
If checkbox is checked, redirect to projectlist.php?showpastdate
When URL = projectlist.php?showpastdate, make checkbox checked.
When URL = projectlist.php?showpastdate and checkbox gets unchecked, redirect to projectlist.php, where the checkbox is unchecked.
I think these triggers are the best options?
With .PHP I'll do:
if (isset($_GET['showpastdate']))
{
<tr style: display: none>
}
else
{
<tr>
}
Maybe someone has an even better solution? I'd like to hear!
Thanks.
EDIT
The javascript I now have is:
<script>
function toggleAutoRefresh(cb) {
if (cb.checked) {
window.location.replace("?showpastdate");
}
// If a checkbox named "cb" is checked, and the url contains "?showpastedate"
if ((cb.checked) && !~window.location.href.indexOf("?showpastdate")) {
//Uncheck the checkbox and remove the "?showpastedate" from the url
document.getElementById("showpastdate").checked = false;
window.location.href.replace("?showpastdate","");
} else {
// Else, check the checkbox and add the "?showpastedate" to the url
document.getElementById("showpastdate").checked = true;
window.location.href += "?showpastdate";
}
}
</script>
After checking the checkbox, it goes to the page projectlist.php?showpastdate and gets unchecked there. When checking again, it goes to projectlist.php?showpastdate?showpastdate. It should remove the ?showpastdate, not add another.
This is could do with PHP too, but I really donĀ“t like a submit button for this checkbox. Just check and execute.
Okay. I got it.
<script>
function toggleAutoRefresh(cb) {
if (~window.location.href.indexOf("?hidepastdate") == 0){
window.location.replace("?hidepastdate");
document.getElementById("showpastdate").checked == true;
}
if (~window.location.href.indexOf("?showpastdate") == 0){
window.location.replace("?showpastdate");
document.getElementById("showpastdate").checked == true;
}
}
</script>
Now the URL gets toggled every time at clicking and PHP does the CSS display work.
Thanks for the effort and for pointing me to the right direction, Cerbrus! Saved me alot of time.

Limiting range of input field

Though it is a very common question. I have one input field in which the data entered must be between 1 and 150.
Problem is I am already using some validations on that. That validation is being used by many other input fields. So I cannot change that. It is the num() function.
On one field mesure I want to add extra functionality. I tried it with validate.
I don't know how to merge these two validations for only one input field using both function in document.ready.
I can do it in either jQuery or PHP.
<input type="text" name='mesure' class="numbersonly" maxlength="3" onblur =" validate()"/>
function num() {
$(".numbersonly").bind('keypress', function(e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
$("#errmsg").html("numbers please");
return false;
}
});
}
function validate()
{
if( document.form.mesure.value >150 )
{
alert( "out of range!" );
document.form.mesure.focus() ;
return false;
}
}
Why not using onkeypress/onkeyup, check it using the validate function.
But remember that javascript is not the real solution for limitation - People can turn of or change the javascript. Also use php for checking the value.
For example, if your input field that you want to limit has the id #text, you can use
if($('#text').val().length>150){
//do stuff here
}
As you will probably post the entered value to some place in the backend, the real validation must happen in php. There, you can do something like
<?php
if(strlen($_POST['text'])>150){
echo "too long";
exit;
}
//do other backend stuff here
?>
Using javascript for validation is only good in so far as it gives the user immediate feedback whether he did something wrong. However, a client can always see client side code like jQuery/Javascript, so for ultimate validation use php.

Keyup if statement for indexOf string acting odd?

I've got a small problem with the following code:
$('#body').keyup(function(){
var i = $('#body').val();
if(i.toLowerCase().indexOf("contact") >= 0){
$('#tosviolation').fadeIn('fast');
$('#sendForm').attr('action','send.php?f=1');
$('.toscontent').html("TOS Breach!");
} else {
$('#tosviolation').fadeOut('fast');
$('#sendForm').attr('action','send.php?f=0');
}
if(i.toLowerCase().indexOf("#") >= 0){
$('#tosviolation').fadeIn('fast');
$('#sendForm').attr('action','send.php?f=1');
} else {
$('#tosviolation').fadeOut('fast');
$('#sendForm').attr('action','send.php?f=0');
}
});
It checks whether #body (textarea) contains the values "contact" or/and "#", and if this textarea does contain said values, it pops up / flashes a div telling the user that they're violating the TOS. With the "#", the box stays there when the user types it, yet when the user types "contact", the box just flashes a few times and goes away, I'm guessing since "#" is 1 char long, and "contact" is 7 chars long, it's something to do with that.
Then again, this is quite strange? I was intending it to just fadeIn() and stay faded in. I didn't mind the flash, because of course, on keyup it'll have to run the function every time the user taps a key, so that's fine, but I can't figure out how to keep it there when the user types "contact" somewhere in the textarea. Also, the other part where the it's using the .attr() is directing the user to send.php, if it does contain "contact","#" -- Then it pushes them to send.php?f=1, and if not, then send.php?f=0 -- #sendForm is the ID of a form tag I have earlier, I assume this already works fine.
Does anyone know how to get the box to stay there once it's pulled up with the data "contact" ?
Try this. Remember, setting the attribute of a form and relying on it for server-side processing is dangerous - the end user can easily fiddle with this before posting. You should validate again with the server and not use any GET variables sent with the form.
$('#body').keyup(function () {
var i = $('#body').val();
if (i.toLowerCase().indexOf("contact") >= 0 || i.toLowerCase().indexOf("#") >= 0) {
$('#tosviolation').fadeIn('fast');
$('#sendForm').attr('action', 'send.php?f=1');
$('.toscontent').html("TOS Breach!");
} else {
$('#tosviolation').fadeOut('fast');
$('#sendForm').attr('action', 'send.php?f=0');
}
});
The problem is that when you're typing "contact", you don't have the "#" symbol. So your first if statement for contact evaluates to true, and fades in #tosviolation. However, the next if statement evaluates to false, so it fades it back out straight away. You'll need to restructure your if statements (likely using an OR condition, rather than two separate if statements) to avoid this.
Something like this should work:
$('#body').keyup(function() {
var i = $('#body').val();
var contact = i.toLowerCase().indexOf("contact");
var atsymbol = i.toLowerCase().indexOf("#");
if (contact >= 0 || atsymbol >= 0) {
$('#tosviolation').fadeIn('fast');
$('#sendForm').attr('action', 'send.php?f=1');
if(contact >= 0) {
$('.toscontent').html("TOS Breach!");
}
} else {
$('#tosviolation').fadeOut('fast');
$('#sendForm').attr('action', 'send.php?f=0');
}
});
Why don't you just check this once, when the field loses focus or before formsubmit? This is easier and cleaner then checking on every keyup event.
I strongly recommend to check the Input on serverside again. simply adding f=1 or f=0 can be manipulated easily. Also think about what happened if the user disabled js.

how to avoid enduser from giving urls in textarea jquery

I want to avoid user from submitting website URLs in text-area using (JQuery) client side validation. I am using Validation plug-in.
Example:
http://www.example.com
I need to validate when user types http:// or www in text-area
You could use a custom function with a matching regex like this:
$.validator.addMethod('no_url', function validatePositionNummer(value){
var re = /^[a-zA-Z0-9\-\.]+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)$/;
var trimmed = trim(value);
if( trimmed == ''){
return true;
}
return trimmed.match(re);
},"No URLs allowed!");
Then you just add your new custom validation method to the element:
$("#your_form").validate({
textarea: no_url
});
You would have to fine-tune the regex ofcourse.
URLs or Links? There is a difference.
However, in either case, don't forget to check on the backend too. You can't trust client side validation. It should only be used to make the user's life easier.
#BernardMarx Thanks for the solution.
Here i used extra regex to validate protocols according to my requirement. Now i need to validate at the end. suggestion please..
For Example:
http://www.example.com/index.php
http://www.example.php/home/
$.validator.addMethod('no_url', function validatePositionNummer(value){
var re = /^[a-zA-Z0-9\-\.\:\\]+\.(com|org|net|mil|edu|COM|ORG|NET|MIL|EDU)$/;
var re1 = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
var trimmed = $.trim(value);
if( trimmed == '' ){
return true;
}
if( trimmed.match(re) == null && re1.test(trimmed) == false){
return true;
}
},"No URLs allowed!");

how to eliminate space in forms in 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.

Categories