如何在没有在文本框中输入任何值的情况下按下特殊字符和提交按钮时显示错误消息?

时间:2018-04-16 10:00:05

标签: php html

<!DOCTYPE html>
<html>
<body>

<?php

if (isset($_POST['txt'])) {
if (!empty($_POST['txt'])){
$veggies = array("Potato", "Cucumber", "Carrot", "Orange", "Green Beans", "onion");
$fruits  = array("Apple", "Banana", "orange", "Pineapple", "Grapes", "Watermelon");
$salad   = array_merge ($veggies, $fruits);
$Object = $_POST['txt'];
$search = array_filter($salad, function($list) use ($Object) {
    return ( stripos($list, $Object) !== FALSE );
});
 print_r($search);

} 

 else {  
    echo 'Enter Item'; 

 }

}

?>
<form method="POST">
Search item:  <input type="text" name="txt" ><br> <br>
      <input type="submit">
</form>

</body>
</html>

如果输入特殊字符(如@,/。etc)时如何显示错误消息,则只允许使用字母。我正在尝试几天但无法解决问题。任何人都可以指导我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

            <!DOCTYPE html>
            <html>
            <body>

            <?php

            if (isset($_POST['txt'])) {
            if (!empty($_POST['txt'])){
            $veggies = array("Potato", "Cucumber", "Carrot", "Orange", "Green Beans", "onion");
            $fruits  = array("Apple", "Banana", "orange", "Pineapple", "Grapes", "Watermelon");
            $salad   = array_merge ($veggies, $fruits);
            $Object = $_POST['txt'];
            $search = array_filter($salad, function($list) use ($Object) {
                return ( stripos($list, $Object) !== FALSE );
            });
             print_r($search);

            } 

             else {  
                echo 'Enter Item'; 

             }

            }

            ?>
   <script type="text/javascript">
   function validateInput(e){
        var key;
       document.all ? key = e.keyCode : key = e.which;
   if ((key > 64 && key< 91) || (key > 96 && key< 123) || key == 8 ||key == 32) {
            alert("Invalid input");

           }
    }

    function validateForm() {
           var value = $("#submitbtn").val();
           if(value == NULL) {
             alert("Please enter input value");
             return false;
           }

    }
            </script>
            <form method="POST">
            Search item:  <input type="text" name="txt" onkeypress="return validateInput(event)"/><br> <br>
                  <input type="submit" name="submit" value="submit" id="submitbtn" onsubmit="return validateForm();">
            </form>

            </body>
            </html>