Page 1 of 1

How to check if a variable contains only safe characters?

Posted: 22 Sep 2016 10:41
by (_osd_)
See title, so I only want alphanumeric characters after a scan.
So that for example "$*[]?/{}bob" will throw out an error.

How can you do this?

Re: How to check if a variable contains only safe characters?

Posted: 22 Sep 2016 11:13
by aGerman
FOR /F may help

Code: Select all

@echo off &setlocal
set "alnum=ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"

set "myvar=$*[]?/{}bob"

set "invalid="&setlocal EnableDelayedExpansion
for /f "delims=%alnum% eol=%alnum:~,1%" %%i in ("!myvar!") do set "invalid=1"
endlocal&set "invalid=%invalid%"

if defined invalid (echo invalid) else echo valid
pause


Steffen

//EDIT Dave is right. EOL should have been set to one of the valid characters. Corrected above.

Re: How to check if a variable contains only safe characters?

Posted: 22 Sep 2016 11:22
by dbenham
Assume your string is in variable var

Option 1: (Basically same as aGerman's answer)

Code: Select all

setlocal enableDelayedExpansion
for /f "delims=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 eol=a" %%A in ("!var!") do (
  REM This is an error condition
  echo Invalid character found
)

Option 1A: (if you want an else condition)

Code: Select all

setlocal enableDelayedExpansion
(for /f "delims=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 eol=a" %%A in ("!var!") do (
  REM This is an error condition
  echo Invalid character found
)) || (
  REM This is a success condition
  echo All characters are valid
)

Option 2:

Code: Select all

setlocal enableDelayedExpansion
echo(!var!|findstr /i "[^abcdefghijklmnopqrstuvwxyz0123456789]" >nul && (
  REM This is an error condition
  echo Invalid character found
) || (
  REM This is a success condition
  echo All characters are valid
)


Dave Benham