Question

Trying to create a basic username check that only allows letters, numbers and the underscore.. anything else should prompt again for user input...

Honestly doing my head in trying to find some better explanations and examples of doing such a thing with DOS .bat file and findstr, ..the below code doesn't work, still allows symbols like )(&^"% to be entered with other allowed characters...

:setname
set /P username=Enter Username: %=%
echo.%username% | findstr /R "[a-zA-Z0-9_]" >nul 2>&1
if not ErrorLevel 1 (
echo %username%
goto :proceed
)
goto :setname
Was it helpful?

Solution

@ECHO OFF
SETLOCAL
:setname
SET "usrname="
set /P usrname=Enter Username: %=%
IF NOT DEFINED usrname GOTO :eof
echo.%usrname%| findstr /R "[^a-zA-Z0-9_]" >nul 2>&1
if ErrorLevel 1 (
 echo %usrname% - OK
) ELSE (
 echo %usrname% - invalid
)
goto :setname

Two fundamental bugs:

first, you need to find any character that is NOT a..zA..Z0..9

second, you need to NOT echo the SPACE into the findstr as space is always invalid

Note that set /p does not set var to [nothing] on ENTER - it leaves var unchanged, hence you can set the user name to a default value.

USERNAME is a magic variable - instantiated by the system. Logical variablename, but one of a number of presets it's not wise to alter. Try executing SET from the prompt in a new session for a partial list...

OTHER TIPS

@echo off
:input
set "in="
set /p "in=Enter username: "
for /f "delims=1234567890abcdefghijklmnopqrstuvwxyz" %%a in ("%in%") do goto :input
echo "%in%"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top