How to check if a variable contains only safe characters?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
(_osd_)
Posts: 25
Joined: 01 Mar 2015 07:41

How to check if a variable contains only safe characters?

#1 Post by (_osd_) » 22 Sep 2016 10:41

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?

aGerman
Expert
Posts: 4678
Joined: 22 Jan 2010 18:01
Location: Germany

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

#2 Post by aGerman » 22 Sep 2016 11:13

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.

dbenham
Expert
Posts: 2461
Joined: 12 Feb 2011 21:02
Location: United States (east coast)

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

#3 Post by dbenham » 22 Sep 2016 11:22

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

Post Reply