[Tutor] validating user input for cli app

Alan Gauld alan.gauld at btinternet.com
Thu Oct 7 15:45:56 CEST 2010


"Rance Hall" <ranceh at gmail.com> wrote


> I'd like to be able to just ask the question again, and re-validate
> the new input or offer a "press q to quit" option

Thats what loops are for...

> The old GOTO syntax that everybody hates was ideal for this type of
> thing, if validation fails, just goto the question again and re-ask
> it.

Nope, it wasn't ideal and thats why it was removed from most 
languages.
Structured Loops are better.

> So how do you do this?

You either write a loop that cycles until you get valid input or you
could create a heirarchy of Field classes(*) that know how to request 
input
and validate it. If the data is invalid they request input again - 
which
takes us back to loops...

(*) Or even a single Validator class that takes a validation function 
as
an input parameter....

One possible loop would look something like:

a = b = c = None
dataOK = False
while not dataOK:
    if not a:
       a = raw_input('Enter a: ')
       if not validA(a):
          a = None
          continue
    if not b:
       b = raw_input('Enter b: ')
       if not validB(b):
          b = None
          continue
    if not c:
       c = raw_input('Enter a: ')
       if not validC(c):
          c = None
          continue

And since the input blocks are repeated you could even
convert them to a function if you really cared or had a lot
of fields.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list