Search code examples
batch-filespecial-charactersfindstrerrorlevel

How to exclude the input of special characters in Batch using findstr?


I'm writing a Batch game and am having some difficulty. I'm making a character creation, and the player can input a name of their choice. I'm trying to detect if they type in special characters by using the findstr command. I've been looking around, but all the other fixes on this website haven't been working for me. I'm not very advanced in Batch, so a simple answer would be preferred, otherwise a detailed explanation would be much appreciated. Delayed expansion is enabled. Here is the code I have.

:charactername
cls
echo We know your Username is !username!, but what will your character's name be?
echo.
set /p character="Type a character name.> "
if "!character!"=="" (
    echo Please type a valid name.
    timeout 3 /nobreak > nul
    goto charactername
)
echo !character! | findstr /R " ^^! @ # $ %% ^ && * ) ( _ = + \] \[ } { \ | ; : "" < > ^, \. / ? ^` ~ 1 2 3 4 5 6 7 8 9 0" 2>nul
if %errorlevel%==0 (
    cls
    echo Please do not use any special characters or numbers for your character's name.
    echo Only - and ' are accepted.
    timeout 5 /nobreak > nul
    goto charactername
) else (
    goto nameconfirm
)

This is what I want each section to do.

if "!character!"=="" detects if the player enters nothing. This is working fine.

echo !character! | findstr /R " ^^! @ # $ %% ^ && * ) ( _ = + \] \[ } { \ | ; : "" < > ^, \. / ? ^` ~ 1 2 3 4 5 6 7 8 9 0" 2>nul : I want this section to detect if the player entered any of these characters. I'm not sure if this command is formatted correctly; please advise.

if %errorlevel%==0 : Based on my other research on StackOverflow, apparently I can use this to detect if the findstr command found any of the special characters. I have also tried using if %errorlevel%==1. The problem here is that if I use the first option, it skips to the else section regardless of special characters. If I detect if the errorlevel is at 1, it doesn't allow anything through, displaying the error message I wrote.


Solution

  • One option would be to use a FOR /F command and use all the characters of the alphabet as delimiters. If the FOR command outputs any data then you know they didn't use only alpha characters.

    for /F "delims=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" %%G IN ("%character%") Do IF NOT "%%~G"=="" @ECHO Bad Character Name