如何在文本框为空或含特殊字符时点击提交按钮显示错误提示
Solution for Input Validation (Empty & Special Characters)
Got it, let's fix this up properly. Your current code only checks for empty input, but we need to add special character validation and make error messages clearer. Also, you were missing the actual HTML form to let users input text and submit it—let's add that too.
Here's the complete, updated code with all required validation:
<!DOCTYPE html> <html> <body> <?php // Initialize error message and results variables $error = ''; $searchResults = []; if (isset($_POST['submit'])) { $input = trim($_POST['txt']); // Check if input is empty (after trimming spaces) if (empty($input)) { $error = '*Error: Please enter some text before submitting!*'; } // Check for special characters (allow only letters and spaces) elseif (preg_match('/[^a-zA-Z\s]/', $input)) { $error = '*Error: Special characters are not allowed! Please use only letters and spaces.*'; } // If validation passes, run the search logic else { $veggies = array("Potato", "Cucumber", "Carrot", "Orange", "Green Beans", "onion"); $fruits = array("Apple", "Banana", "orange", "Pineapple", "Grapes", "Watermelon"); $salad = array_merge($veggies, $fruits); $searchResults = array_filter($salad, function($item) use ($input) { return stripos($item, $input) !== false; }); } } ?> <!-- Show error message if validation fails --> <?php if (!empty($error)): ?> <p><?php echo $error; ?></p> <?php endif; ?> <!-- HTML Form for user input --> <form method="POST" action=""> <input type="text" name="txt" placeholder="Enter a fruit/veggie name..."> <button type="submit" name="submit">Submit</button> </form> <!-- Display formatted search results --> <?php if (!empty($searchResults)): ?> <h3>Search Results:</h3> <ul> <?php foreach ($searchResults as $result): ?> <li><?php echo $result; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> </body> </html>
Key improvements made:
- Added a proper HTML form so users can actually input text and submit it (your original code was missing this critical piece)
- Added empty input validation with a clear, user-friendly error message
- Added special character validation using a regex pattern (
/[^a-zA-Z\s]/), which blocks any characters that aren't letters or spaces - Organized code into logical sections (validation, form, results) for better readability
- Replaced raw
print_r()output with a clean unordered list to display search results - Used
trim()on input to ignore accidental leading/trailing spaces that might trigger false "empty" errors
How the validation flows:
- When the user clicks "Submit", we first trim extra spaces from their input
- If the input is empty after trimming, we show the empty input error
- If the input contains invalid characters, we show the special character error
- Only when both checks pass do we run the search and display results
内容的提问来源于stack exchange,提问作者user9620159
相关产品推荐
相关产品推荐

