How-to: sanitize user input - sanitize.cmd

Sanitize an input string omitting any non-approved characters from the output.

@ECHO OFF
Setlocal
:: Sanitize an input string omitting any non-approved characters from the output
CALL Set "_string=%%%~1%%"
Set "_sanitizedString="

:sanitizeLoopStart
IF "%_string%"=="" (GOTO :sanitizeLoopEnd)
FOR %%A 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 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 1 2 3 4 5 6 7 8 9 0 ' . - # $ + ? @ [ ] { } ~ ) DO (
   IF "%_string:~0,1%"=="%%A" (
      Set "_sanitizedString=%_sanitizedString%%%A"
   )
)
Set "_string=%_string:~1%"
GOTO :sanitizeLoopStart

:sanitizeLoopEnd
ENDLOCAL & Set "_sanitizedResult=%_sanitizedString%"

Credits: Michael Wright/Simon Sheppard, see forum thread

Examples

Prompt for input and then sanitise:

Set /P _ans=Please enter a Department:

:: remove &’s and quotes from the answer (via string replace)
Set _ans=%_ans:&=%
Set _ans=%_ans:"=%

:: Sanitize
CALL sanitize.cmd _ans
Echo "%_sanitizedResult%"

“I quite like post-apocalyptic films, things like 'Mad Max' for instance, because they are so full on and there is something quite cleansing about the post-apocalyptic because you can see where we all think we’re heading” ~ Anthony Daniels

Related commands

SET /p - Prompt for user input.
CHOICE - Accept keyboard input to a batch file.


 
Copyright © 1999-2024 SS64.com
Some rights reserved