Wednesday, December 12, 2012

input validation in visual basic


Input Validation: Good portions of program errors come from unexpected user input or responses. “How do I prevent a user from entering a letter into a Text Box intended for numbers?” In short, input validation really involves a talented programmer with enough foresight to prevent errors before they happen.
Validate Event: Most Visual Basic controls have a validate event that occurs right before the control loses focus. However, this event is not always triggered by default. To ensure it does, you can set the CausesValidation property of the control to true.
Private Sub Form_Load()
Text1.CausesValidation = True
End Sub
The validate event of the Text Box takes the Boolean variable Cancel as an argument:
Private Sub Text1_Validate(Cancel As Boolean)
If Text1.Text = “A” Then
Cancel = False
Else
Cancel = True
End If
End Sub
If the user enters the letter A into the Text Box, I set the Cancel parameter to false. This lets the user move on to the next control. However, if the user enters anything else, I set the cancel parameter to true, essentially preventing the user from going anywhere.
Checking Data Types: Sometimes, preventing input errors can be as easy as determining whether a user has entered a number or a string. You might want the user to enter his or her name, or maybe you are looking for a number such as an age. Either way, Visual Basic provides the IsNumeric function for testing such scenarios.
The IsNumeric function takes a variable or expression as a parameter and returns a Boolean value of true if the variable or expression is a number and false if it is not. You can use the IsNumeric function in conjunction with the validate event for checking data types:
Private Sub Text1_Validate(Cancel As Boolean)
If IsNumeric(Text1.Text) = True Then
Cancel = False
Else
Cancel = True
End If
End Sub
Testing a Range of Values: You might find at times that testing a value for a particular data type is not enough to prevent input errors. Sometimes, it is necessary to check for a range of values. For example, you might want to prompt a user to enter a number from 1 to 100. Or maybe you want a person to choose a letter from a to z

Private Sub Text1_Validate(Cancel As Boolean)
If IsNumeric(Text1.Text) = True Then
If Val(Text1.Text) >= 1 And Val(Text1.Text) <= 100 Then
Cancel = False
Else
Cancel = True
End If
Else
Cancel = True
End If
End Sub