Only accept a numeric number.
Posted: 30 Jul 2020 09:54
Good afternoon!
I want to be able to use the user input value as a variable further down some code rather than having to hard code the number.
The code below works, but it relies on the fact that there actually is a number input and it is a number that is valid. Here is the test code I have got . . .
The code above doesn't accept the user just hitting <ENTER> and returns them to the :Menu, that's OK.
The code above doesn't accept the user inputting a number greater than 12 and returns them to the :Menu, that's OK.
What I can't seem to be able to do is to make sure that ONLY a number is input. If I input a letter, it accepts it. If a letter is entered I want it to give the same message and goto :Menu. I ONLY want it to accept numbers 1,2,3,4,5,6,7,8,9,10,11,12.
I have scoured the Internet for a long time but been unable to come up with anything close to what I want to achieve.
I found this bit of code [ which I have tried to adapt ] which looked promosing but I can't get it ignore letters and ONLY accept numbers!
Any help will be greatly appreciated.
Thanks in advance.
I want to be able to use the user input value as a variable further down some code rather than having to hard code the number.
The code below works, but it relies on the fact that there actually is a number input and it is a number that is valid. Here is the test code I have got . . .
Code: Select all
@echo off
setlocal enabledelayedexpansion
:Menu
set "userinput="
set /p "userinput=Write something . . ."
if "%userinput%"=="" echo. & echo Invalid & echo. & echo ^>Press ANY Key to try again . . . & pause >nul & goto :Menu
if "%userinput%" gtr 12 echo. & echo Invalid & echo. & echo ^>Press ANY Key to try again . . . & pause >nul & goto :Menu
echo. & echo %userinput%
pause & goto :Menu
The code above doesn't accept the user inputting a number greater than 12 and returns them to the :Menu, that's OK.
What I can't seem to be able to do is to make sure that ONLY a number is input. If I input a letter, it accepts it. If a letter is entered I want it to give the same message and goto :Menu. I ONLY want it to accept numbers 1,2,3,4,5,6,7,8,9,10,11,12.
I have scoured the Internet for a long time but been unable to come up with anything close to what I want to achieve.
I found this bit of code [ which I have tried to adapt ] which looked promosing but I can't get it ignore letters and ONLY accept numbers!
Code: Select all
echo %userinput%|findstr /r /c:"^[0-9][0-9]*$" >nul
if errorlevel 1 (
echo. & echo Invalid & echo. & echo ^>Press ANY Key to try again . . . & pause >nul & goto :Menu
) else (
set "OS_Index=%userinput%
)
Thanks in advance.