Press enter to skip the top menu

Programming User Interface

Validating User Input

NCEA Compatibility

Module: AS91883 Develop a computer program

Requirements: using methods, functions, procedures, actions, conditions and control structures effectively, checking input data for validity, input from a user, user-defined methods, functions or procedures.

Go to top

Learning Outcomes

On completing this page you will know how to use while loops to validate incoming user data.

Go to top

Heuristics Used

Go to top

Introduction

The basis of a good user interface is simply common sense. In the previous page we looked at a program that had the bare bones of a payroll procesing program.

Although we were not even considering a user interface at the time, by default we satisfied two heuristics: #2 Match between system and the real world and #6 Recognition rather than recall.

We complied with #2 by using plain, non technical language. We complied with #6 by informing the user of the upper and lower limits of the values required for each of the three inputs. You can check this out in lines 11 to 13 of the page 'A Simple Program'

To comply with #1 we needed to add an extra line at the end of the code informing the user that the data had been saved to the file.

So what else do we need to do to upgrade the usability of our program?

To find out what else can be done to improve the accessibility of our program we need to look at Fig 1 of the page 'A Simple Program'. Examining this we find that on the second running of the program the user has entered 5 for the super code. This is a wrong value because only values between 0 and 3 are allowed. Despite this the program went ahead and processed the rest of the payroll data. On the third running all of the input data is wrong but the program still goes ahead with the processing.

This should not be allowed to happen.

To overcome this problem we need to test each input item to ensure that it is within the specified minimum and maximum values specified for that item. If it is then we will accept it. If it is not we shall inform the user that the data was invalid and ask them to enter it again. This set of steps continues until a data item in the correct range is received from the user. For performing this continuous testing we need a while loop.

In our current program we have three data items we need to check for validity: hours worked, hourly rate and super code. We shall therefore need three while loops: one for each of the data items we need to check. Below in Listing 1 is an example of the program for performing those validation checks.

Go to top

Validating user Input

Listing 1
                        #declaration of variables
                        fltHours=0.0
                        fltRate=0.0
                        fltSuper=0.0
                        fltGross=0.0
                        fltTax=0.0
                        fltNet=0.0
                        fltSuper=0.0
                        intSuperCode=0
                        #user input
                        #**********************************************************************************************
                        #The next 5 lines after the comment form a while loop that ensures that any value being stored in the
                        #variable fltHours will be a number between 5 and 60 inclusive
                        #***********************************************************************************************
                        fltHours = float(input("Enter value for hours worked. Value must be between 5 and 60 :"))
                        while fltHours <5 or fltHours > 60:
                            strErrMsg = "The value of hours must be between 5 and 60. You have entered a value of " + str(fltHours)
                            print(strErrMsg)
                            fltHours = float(input("Enter value for hours worked. Value must be between 5 and 60 :"))
                        #***********************************************************************************************
                        #The 5 lines after this code validates the rate as being in the range 20 to 80 inclusive
                        #***********************************************************************************************
                        fltRate = float(input("Enter value for rate. Value must be between 20 and 80 :"))
                        while fltRate < 20 or fltRate > 80:
                            strErrMsg = "The value of rate must be between 20 and 80. You have entered a value of " + str(fltRate)
                            print(strErrMsg)
                            fltRate = float(input("Enter value for rate. Value must be between 20 and 80 :"))
                        #**********************************************************************************************
                        #The 5 lines after this code validates the super code as being in the range 20 to 80 inclusive
                        #************************************************************************************************
                        intSuperCode = int(input("Enter superannuation code. Value must be one of 0, 1, 2 or 3 :"))
                        while intSuperCode < 0 or intSuperCode > 3:
                            strErrMsg = "The value of the super code must be an integer between 0 and 3. You have entered a value of " + str(intSuperCode)
                            print(strErrMsg)
                            intSuperCode = int(input("Enter superannuation code. Value must be one of 0, 1, 2 or 3 :"))
                        #calculation
                        fltGross = fltHours * fltRate
                        fltTax = fltGross * 0.25;
                        if intSuperCode == 0:
                            fltSuper = 0
                        elif intSuperCode == 1:
                            fltSuper = fltGross * 0.05
                        elif intSuperCode == 2:
                            fltSuper = fltGross * 0.1
                        elif intSuperCode == 3:
                            fltSuper = fltGross * 0.15
                        else:
                            print("Wrong value for super code")
                        fltNet = fltGross - fltTax - fltNet - fltSuper
                        #display results
                        print("Gross: ", fltGross)
                        print("Tax:   ", fltTax)
                        print("Super  ", fltSuper)
                        print("Net:   ", fltNet)
                        #Save calculated data to a file
                        myfile=open('Payroll File.txt','a')
                        myfile.write(str(fltHours) +"\n")
                        myfile.write(str(fltRate) +"\n")
                        myfile.write(str(fltGross) +"\n")
                        myfile.write(str(fltTax) +"\n")
                        myfile.write(str(fltNet) +"\n")
                        myfile.close()
                        print("Data has been saved to the file")
                    

The above program is an extension of Listing 1 in the previous section. The difference between them is that the user input section now spans lines 11 to 35. Other than the comments this consists of three while loops which iterate indefinitely until the user enters a value in the expected range.

The first of those loops spans lines 15 to 19. This loop controls the data destined for the variable fltHours.

Line 15 contains the priming read for this loop. The prompt of the input function informs the user what data type they are entering and what range of values are allowed, 15 to 60 in this case.

At line 16 the condition of the while loop tests the newly received data for being outside the allowed range. If this is the case then the body of the loop is activated. The body of the loop consists of lines 17 to 19. At line 17 it builds up an error message. This consists of two sentences: the first sentence explainis the data to be entered and the second sentence showing what the user actually entered. These two pieces of information are stored in the appropriately named string variable strErrMsg

At line 18 this is printed for the user to see

At line 19 the user is again prompted to enter a value for the hours worked. Notice that this line is identical to line 15 except that it is indented one tab space. This is because it is part of the body of the loop.

Once this line is executed control passes back to line 16 where the variable fltHours is once again tested

On the other hand if the value entered is within the correct range the loop terminates and control passes to line 23. Here we begin another while loop for testing the value of the hourly rate. In both structure and execution this loop is identical to the one that we just examined and for this reason there is no need to explain it.

At line 31 we have our final testing loop. This time we are testing an integer variable instead of a floating point vairable. Apart from this the loop is idientical in structure and processing to the two preceding loops.

Below is a sample output from the program.

Output from the program where data is validated using a while loop
Fig 1:This shows that a number of attempts have been made to enter each data item before a valid one was entered

From Fig 1 above we seee that two false values for the hours worked were entered and then rejected, before a correct value of 40 was entered.

Two false values for the hourly rate were entered and rejected before a correct value of 30 was entered.

Finally two false values for the super code were entered before the correct value of 2 was entered.

Once valid data for hours, rate and super code had been received the program went ahead with the calculation. It then printed out the gross, tax and net before saving the data to the file and then informing us that the data was saved.

Go to top

Discussion on #5: Error prevention

On the N/N website the elaboration on this heuristic states that "Good error messages are important, but the best designs carefully prevent problems from occurring in the first place." In this case our problems were caused by no restrictions on what data the user could enter.

In the case of hours worked we determined that for any pay period nobody worked less than 5 hours and also nobody worked more than 60 hours. Thus the value for the hours had to be 5 to 60 inclusive. We implemented this in our program by having the following condition on our while loop:

fltHours <5 or fltHours > 60

If a number outside of this was entered the body of the loop was activated, the user was informed of the error and the user was asked to reenter the value for the hours.

The loop's condition tested the new value. If it was within the 5 to 60 range then the loop terminated and control passed to line 23.

If, however, the value was outside of this range, i.e. if it was less than 5 or greater than 60, then the body of the loop would be activated again and the user would once more be requested to enter a correct value for the hours.

The end result here would be that a user determined to enter a wrong value for the hours worked would be forever trapped inside this loop.

This loop construct prevents erroneous data being entered for the hours worked.

The above six paragraphs were referring to the loop that spans lines 15 to 19 of Listing 1 above. What we have said about that loop also applies the the loops that span lines 23 to 27 and 31 to 35.

As applies to our example program here the requirements of Heuristic #5 have been met.

Go to top

Discussion on #9: Help users recognize, diagnose, and recover from errors

The elaboration on this heuristic states that "Error messages should be expressed in plain language (no error codes), precisely indicate the problem, and constructively suggest a solution."

Still referring to the loop that spans lines 15 to 19 of Listing 1 above we have taken the following steps to adhere to the requirements of heuristic #9:

As applies to our example program here the requirements of Heuristic #9 have been met.

Go to top