inputvbscriptinputboxvalidating

Validating user input in inputbox


When I run the following snippet, and enter an acceptable value, I get the desired result.

do while len(strselect) = 0  'or strselect<>"1" or strselect<>"2" or strselect<>"3"
strselect = inputbox ("Please select:" &vbcrlf&vbcrlf&_  
"1. Add an entry" &vbcrlf&vbcrlf&_  
"2. Remove an entry" &vbcrlf&vbcrlf&_  
"3. Search for an entry" &vbcrlf, "Contact Book")
if isempty(strselect) then
wscript.quit()
elseif strselect="1" then
wscript.echo "You chose 1"
elseif strselect="2" then
wscript.echo "You chose 2"
elseif strselect="3" then
wscript.echo "You chose 3"
end if
loop

However if I try constrain the validation process further (by including the remark in the do while conditions), and run the snippet again, I get the corresponding if condition triggered, but the do loop continues, instead of exiting.

I've tried using isnumeric and cstr on the do loop strselect conditions, with no joy... What am I missing to get the darn thing to exit the loop?


Solution

  • You have a problem with the logic in the condition

             condition 1            condition 2       condition 3       condition 4
             v----------------v     v------------v    v------------v    v............v
    do while len(strselect) = 0  or strselect<>"1" or strselect<>"2" or strselect<>"3"
    

    Depending on value inside strselect, you have

    value   c1      c2      c3      c4    
            len=0   <>"1"   <>"2"   <>"3"    c1 or c2 or c3 or c4
    --------------------------------------   --------------------
    empty   true    true    true    true            true
      1     false   false   true    true            true
      2     false   true    false   true            true
      3     false   true    true    false           true
    other   false   true    true    true            true
    

    In each line you have at least one condition evaluated as true, and as you are concatenating the conditions with Or operators (evaluate to true if at least one of the values is true), the full condition is evaluated as true and the code keeps looping

    You only need to change the condition

    Do While strselect<>"1" And strselect<>"2" And strselect<>"3"
    Do While Not (strselect="1" Or strselect="2" Or strselect="3")
    ....