3

I was wondering if it is possible to test a variable to see if it contains anything other than Letters and numbers? I need to have this in order to limit username specs. I have a kind of example script below.

 :top
echo enter a name
set /p name=">"
If contains (Anything other than letters/numbers/dashes) echo Invalid Name. & goto top
echo thank you!
pause

Thanks everyone!

Edit: I would think this is probably a duplicate, however I do not know what to search for to find other posts... Whenever I searched anything related to my question it brought up find and replace in text files or something else unrelated. If anyone can find a duplicate please let me know and I will close this question. Thank you.

Mark Deven
  • 550
  • 1
  • 9
  • 21
  • 1
    I like your edit... but it is not very likely that this is a duplicate. Duplicates really have to be the same question. You should look out for the keyword "validation". like here https://stackoverflow.com/questions/20414027/batch-script-validate-date-input – Harry Nov 07 '17 at 19:35
  • @Harry thanks Harry, Its great to hear that for once... I think a lot of other people do not understand this keyword, maybe the staff should go over this with everyone again. asking on errors with PHP scripts are terrible because they always point it to one that is slightly related whatever the question. Thanks. – Mark Deven Nov 08 '17 at 12:44
  • well it is in deed pretty complex to identify a duplicate and primarily based on opinion. If you dont want some question to be flagged as dup you should paste a link to a similar question and point out whats the difference from yours to the linked one. This shows that you did invest some time to lookup on your own which is mandatory for any question. "proof of research" – Harry Nov 08 '17 at 19:06
  • @Harry I hadn't thought of adding a link thanks. – Mark Deven Nov 08 '17 at 21:21

2 Answers2

4

This work for the majority of ascii characters. It may have some caveats.

@echo off
set /p "name=Enter a name>"
set "test=%name%"
FOR %%G IN ( a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9 ) do (
    IF DEFINED test call set "test=%%test:%%G=%%"
)
IF DEFINED test (
    echo Invalid characters in username:"%test%"
) else (
    echo Good Username: "%name%"
)
pause
Squashman
  • 13,649
  • 5
  • 27
  • 36
  • Rojo's was a bit more condensed so I used that, however I like the easy customization of your script. thanks. – Mark Deven Nov 08 '17 at 12:45
3

This allows only letters, numbers, and dashes:

@echo off & setlocal

:top
set /P "name="Enter a name: "
setlocal enabledelayedexpansion
echo(!name!| findstr /i "[^a-z0-9-]" >NUL && (
    endlocal
    set /P "=Invalid name. " <NUL
    goto top
)

endlocal
echo Thank you %name%!
pause
rojo
  • 24,000
  • 5
  • 55
  • 101