Validating input

A program should check user input to be sure it is valid. For example, consider this payroll program, which checks to be sure the pay rate is greater than zero and less than $80 per hour and the hours worked are between 0 and 60.

Here is the event handler for clicking on the "Calculate Pay" button, along with a flow chart:


Dim Hours, Rate, Gross As Single
Hours = CSng(txtHrs.Text)
Rate = CSng(txtRate.Text)
If Rate > 0 And Rate < 80 And Hours > 0 And Hours < 80 Then
   Gross = Hours * Rate  'compute gross pay
   lblGross.Text = Cstr(Gross)  'display the gross pay
Else
   MessageBox.Show("Rate must be between 0 and 80, hours 0 and 60.")
End If

As you see, the program uses and If...Then...Else statement to decide whether to display an error message or do the payroll computation.

This program allows the user to enter inputs, then checks for errors just before processing them. Another approach is to validate each input as soon as it is entered, not allowing the user to continue until he or she enters valid data.

This payroll program takes the latter approach. It validates the inputs as soon as the user enters the data.

It does the validation when the leave event occurs. If there is an error, it displays the error message, clears the TextBox and returns focus to it.

Which approach do you like best?


Disclaimer: The views and opinions expressed on unofficial pages of California State University, Dominguez Hills faculty, staff or students are strictly those of the page authors. The content of these pages has not been reviewed or approved by California State University, Dominguez Hills.