obsideus
obsideus

Reputation: 21

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.

Upvotes: 0

Views: 844

Answers (5)

Loktar
Loktar

Reputation: 35309

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;
    }
}

Upvotes: 1

regality
regality

Reputation: 6554

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>

Upvotes: 0

Ry-
Ry-

Reputation: 224942

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
}

Upvotes: 3

Icarus
Icarus

Reputation: 63966

Just take the string, trim the initial and final spaces and check the length; if length is 0, don't submit the form.

Upvotes: 0

SeanCannon
SeanCannon

Reputation: 77976

Wrap your query variable in an empty condition:

if(!empty(trim($_POST['searchterm']))
{
   // do search
}

Upvotes: 6

Related Questions