@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...