Sunday, October 11, 2009

Textbox validation for numeric values


A variable that is declared as numeric ( integer, decimal, ….etc.) can only contain numbers 0 through 9. For example look at the following code:
Dim intTest1 As Decimal

Move Form objects into variables
intTest1 = txtTestScore.Text

Program Crash
If the user were to enter any characters other than 0 through 9 in the txtTestScore text box or if left empty (in which case the text box contains blanks), the assignment statement would fail as the program is trying to push invalid characters into the decimal variable.

Validation
Two type of validation for textboxes where the user would enter numeric values.
1. Check if the entered value is numeric
2. Sometimes, you would want to perform a range checkor check for positive numbers. For example, a test score should be between 0 and 100.

In the following code snippet, note where the contents of the textbox is being moved into the variable – after validating and making sure the contents of the textbox is numeric.

If NOT ISNUMERIC( txtTestScore.text) then
Msgbox(“Enter a valid numeric value”, , “Input error”)

Else

‘Move Form objects into variables
intTest1 = txtTestScore.Text

If intTest1 is less than (<) 0 AND intTest1 gtreater than (>) 0 Then

Msgbox(“Enter a number between 0 and 100”, , “input error’)

Endif
Endif

How will you validate a positive number?

No comments:

Post a Comment