Click here to Skip to main content
15,885,944 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Quote:
How to show Error message when special characters are entered, only letters and space are allowed


What I have tried:

<!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>
Posted
Updated 23-Jun-23 6:08am

1 solution

PHP
if (isset($_POST['txt'])) {
    if (!empty($_POST['txt'])) {
        $input = $_POST['txt'];

        //Check for special characters
        if (preg_match('/^[a-zA-Z\s]+$/', $input)) {
            $veggies = array("Potato", "Cucumber", "Carrot", "Orange", "Green Beans", "onion");
            $fruits  = array("Apple", "Banana", "orange", "Pineapple", "Grapes", "Watermelon");
            $salad   = array_merge($veggies, $fruits);

            $search = array_filter($salad, function($list) use ($input) {
                return (stripos($list, $input) !== FALSE);
            });

            print_r($search);
        } else {
            echo 'Only letters and spaces are allowed.';
        }
    } else {  
        echo 'Enter an item.'; 
    }
}


If you also allow numbers, you can use the regular expression '/^[a-zA-Z0-9\s]+$/'!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900