Abstract

snippet(JAVA).sanitizeInput

#RAW the menu

         boolean running = true;
            while (running) {
                displayMainMenu();
                String choice = scanner.nextLine();
                log("User selected option: " + choice);
                
                switch (choice) {

#RAW: from a menu in https://github.com/kvnbbg/feenysh

                switch (choice) {
                    case "1":
                        interactWithStoryQuestions();
                        break;
                    case "2":
                        if (mathCaptchaChallenge()) {
                            accessGrantedContent();
                        } else {
                            System.out.println(RED + "\nToo many failed attempts. Please try again later." + RESET);
                        }
                        break;
                    case "3":
                        displayContactInfo();
                        break;
                    case "4":
                        System.out.println(GREEN + "\nExiting Feenysh. Thank you for visiting!" + RESET);
                        running = false;
                        break;
                    default:
                        System.out.println(RED + "\nInvalid choice. Please try again." + RESET);
                }


To make the input validation simpler and more robust against non-integer inputs, you can use a loop with hasNextInt() from the Scanner class. Here’s a cleaner approach:

Scanner scanner = new Scanner(System.in);
int choice = 0;

// Get valid integer input
while (true) {
    System.out.print("Enter your choice (1-4): ");
    if (scanner.hasNextInt()) {
        choice = scanner.nextInt();
        scanner.nextLine(); // consume the newline
        if (choice >= 1 && choice <= 4) {
            break;
        } else {
            System.out.println(RED + "\nPlease enter a number between 1 and 4." + RESET);
        }
    } else {
        System.out.println(RED + "\nInvalid input. Please enter a number." + RESET);
        scanner.nextLine(); // clear the invalid input
    }
}

// Now use the validated integer in your switch
switch (choice) {
    case 1:
        interactWithStoryQuestions();
        break;
    case 2:
        if (mathCaptchaChallenge()) {
            accessGrantedContent();
        } else {
            System.out.println(RED + "\nToo many failed attempts. Please try again later." + RESET);
        }
        break;
    case 3:
        displayContactInfo();
        break;
    case 4:
        System.out.println(GREEN + "\nExiting Feenysh. Thank you for visiting!" + RESET);
        running = false;
        break;
}

more simple is:

List<String> validChoices = List.of("1", "2", "3", "4");
String choice = scanner.nextLine();

if (!validChoices.contains(choice)) {
    System.out.println(RED + "\nInvalid choice. Please enter 1-4." + RESET);
    continue;
}

switch (choice) {
    // ... same cases as before ...
}

yes or no

Scanner scanner = new Scanner(System.in);
String userInput;

while (true) {
    System.out.print("Do you want to continue? (yes/no): ");
    userInput = scanner.nextLine().trim().toLowerCase(); // Convert to lowercase for case-insensitivity

    if (userInput.equals("yes") || userInput.equals("no")) {
        break; // Valid input, exit loop
    } else {
        System.out.println(RED + "Invalid input. Please enter 'yes' or 'no'." + RESET);
    }
}

// Now process the valid input
if (userInput.equals("yes")) {
    System.out.println(GREEN + "Continuing..." + RESET);
    // Your logic for "yes"
} else {
    System.out.println(RED + "Exiting..." + RESET);
    // Your logic for "no"
}

To sanitize text inputs (allowing only letters, spaces, and basic punctuation) while rejecting numbers and special symbols, you can use regex (regular expressions) or a simple character-checking loop.


Method 1: Using Regex (Best for Strict Control)

This method checks if the input contains only letters, spaces, apostrophes, hyphens, and basic punctuation (adjust as needed).

import java.util.Scanner;

public class InputSanitizer {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String userInput;

        while (true) {
            System.out.print("Enter your text (no numbers/symbols): ");
            userInput = scanner.nextLine().trim();

            // Regex: Allows letters, spaces, apostrophes, hyphens, and basic punctuation
            if (userInput.matches("^[\\p{L} ,.!?'-]+$")) {
                break; // Valid input
            } else {
                System.out.println("Invalid input! Only letters, spaces, and basic punctuation allowed.");
            }
        }

        System.out.println("Valid input: " + userInput);
        scanner.close();
    }
}

Explanation of Regex:

  • ^ and $ → Match the entire string.
  • \\p{L} → Matches any Unicode letter (supports multiple languages).
  • ,.!?'- → Allows spaces, commas, periods, exclamation marks, question marks, apostrophes, and hyphens.
  • + → Ensures at least one character is present.

Method 2: Manual Character Check (More Control)

If you want strict ASCII-only letters (A-Z, a-z) and reject everything else:

public static boolean isTextOnly(String input) {
    for (char c : input.toCharArray()) {
        if (!Character.isLetter(c) && c != ' ' && c != '\'' && c != '-') {
            return false; // Reject if not a letter, space, apostrophe, or hyphen
        }
    }
    return !input.isEmpty(); // Also ensure input is not blank
}

// Usage:
while (true) {
    System.out.print("Enter your name: ");
    String name = scanner.nextLine().trim();

    if (isTextOnly(name)) {
        System.out.println("Valid name: " + name);
        break;
    } else {
        System.out.println("Invalid! Only letters, spaces, apostrophes, and hyphens allowed.");
    }
}

Method 3: Allow Only Letters (No Punctuation)

If you want strictly alphabetic input (no numbers, symbols, or spaces):

if (userInput.matches("^[a-zA-Z]+$")) {
    System.out.println("Valid alphabetic input.");
} else {
    System.out.println("Only letters A-Z allowed!");
}

MethodBest ForExample Allowed Input
Regex (\\p{L})Multilingual support"José O'Connor"
Manual CheckStrict ASCII letters"John Doe"
Letters Only ([a-zA-Z])Strict alphabetic (no spaces/symbols)"Hello"

Let’s gooooooooo! 🚀


Discover more from Kevin Marville Insights

Subscribe to get the latest posts sent to your email.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Find out more about Webmentions.)