检查<input />是否为空或仅为空格

时间:2014-03-08 01:40:04

标签: html mysql html5 search search-engine

某些网站的搜索框不是很好:当您在搜索栏中放置一个空格并提交时,它会返回他们拥有的每个搜索项。 (例如:http://watchfreemovies.unblocked.co/

我也这样做。如何在提交前验证搜索框中是否有实际文本?

搜索框和按钮:

<div class="Nava">
<input type="button" name="button" id="hello" value="M" />
</div>
    <form action='/search.php' method='GET'>
        <input id='searchbar' type='text' name='search' placeholder="search for movies &  shows" maxlength="50" />
        <input id='submit' type='submit' name='submit' value='Search' />
    </form>
    <div class="Navbuttons">
        <a href="../shows"><input type="button" name="button" id="button" value="shows" /></a>
        <a href="../movies"><input type="button" name="button" id="button" value="movies" /></a>
    </div>

结果页面:

$x = 0;
$construct = '';
$search = $_GET['search'];
$search = preg_replace("#[^0-9a-z ]#i", "", $search);
if (strlen($search) <= 0)
    echo "Search term too short";
else {
    echo "You searched for '<b>$search</b>' ";
    mysql_connect("localhost", "root", "");
    mysql_select_db("search");
    $search_exploded = explode(" ", $search);
    foreach ($search_exploded as $search_each) {
        $x++;
        if ($x == 1)
            $construct .= "keywords LIKE '%$search_each%'";
        else
            $construct .= "AND keywords LIKE '%$search_each%'";
    }
    $construct = "SELECT * FROM searchengine WHERE $construct";
    $run = mysql_query($construct);
    $foundnum = mysql_num_rows($run);
    if ($foundnum == 0)
        echo "<p>Sorry, there are no matching result for '<b>$search</b>'.</p>
    <li> Try different words with similar
     meaning</li>
     <li> make sure you're spelling is correct</li>";
    else {
        echo "$foundnum results found !";

        while ($runrows = mysql_fetch_assoc($run)) {
            $title = $runrows['title'];
            $desc  = $runrows['description'];
            $url   = $runrows['url'];

            echo "
    <hr><a href='$url'><h2><b>$title</b></h2></a><br>
    $desc<br>
    <a href='$url'></a><p>
    "; 
        }
    }

}

1 个答案:

答案 0 :(得分:0)

检查服务器端:

if (!trim($_GET['search'])) {
    echo 'Enter a query.';
}

检查客户端:

<form action='/search.php' method='GET'>
    <input id='searchbar' type='text' name='search' placeholder="search for movies &  shows" maxlength="50" required />
    <input id='submit' type='submit' name='submit' value='Search' disabled />
</form>
<script>
    document.getElementById('searchbar').onkeypress = function() {
        document.getElementById('submit').disabled = !this.value.trim();
    }
</script>

Fiddle