【问题标题】:Check if <input> is empty or only whitespace检查 <input> 是否为空或只有空格
【发布时间】:2014-04-11 09:56:46
【问题描述】:

一些网站的搜索框不是很好:当你在搜索栏中放一个空格并提交时,它会返回他们所有的搜索项。 (例如: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>
    "; 
        }
    }

}

【问题讨论】:

  • 在搜索前修剪字符串并检查长度

标签: mysql html search search-engine


【解决方案1】:

检查服务器端:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-28
    • 2017-08-19
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    相关资源
    最近更新 更多