Advertisement
T3RRYT3RR0R

restrict input to integer between min max range

Dec 1st, 2021 (edited)
550
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Batch 1.72 KB | None | 0 0
  1. ::# :ValidNum Function for accepting input of a positive number, with arguments to declare
  2. ::#  return var, Maximum and Minimum ranges. Scripted to be Proof against code injection.
  3. ::# Blocks entry of: non integer strings, negative numbers, hex, octal, numbers with leading 0's and 0 literal,
  4. ::#  and Integers outside of the declared range.
  5.  
  6.  @Echo off
  7. Rem usage examples:
  8. Rem Example 1 - Return var $RV, Max 31, default Min: 1
  9.   Call:ValidNum $RV 31
  10. Rem Example 2 - Return var $RV2, Max 20, Min: 10
  11.   Call:ValidNum $RV2 20 10
  12. Rem Example 3 - Max default: 2147483647, Min 5, return var default: $Num
  13.   Call:ValidNum "" "" 5
  14.   Set $
  15.  Goto:Eof
  16.  
  17.  :ValidNum [returnvar] [max] [min]
  18. Rem - Forces positive numeric input within min max range.
  19.  SETLOCAL
  20.  Set "sign=-1"
  21.  
  22.  :VNumIn
  23.  %= ensure nul value =%
  24.   Set "input="
  25.  %!! min integer =%
  26.   2> nul Set /a "min=%~3","1/min","1/(sign-(min>>31))","1/(%~2/%~3)" || Set "min=1"
  27.  %!! max integer =%
  28.   2> nul Set /a "max=%~2","1/max","1/(sign-(max>>31))","1/(%~2/min)" || Set "max=2147483647"
  29.  
  30.  
  31.  %= Prompt for input =%
  32.   Set /p "input=Enter a number GEQ %min% LEQ %max%: "
  33.  
  34.  %= Any Input surviving the Below Set /A testing is safe for expansion =%
  35.  %= Input Testing. input +/-         , input > min     , input < max   , Hex/Octal for comparison =%
  36.   2>nul Set /a "1/(sign-(input>>31))","max/(input/min)","1/(max/input)","HexOct=input" || Goto:VNumIn
  37.  
  38.  %= compare assignments to block input of hex, octal or numbers with leading 0's =%
  39.   If not "%Input%"=="%HexOct%" Goto:VNumIn
  40.  
  41.  ( %= return value in Arg1 if used ; else return in $Num =%
  42.   ENDLOCAL & Set "%~1=%input%" 2> nul || Set "$Num=%input%"
  43.   Goto:Eof
  44.  )
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement