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?

Thursday, October 8, 2009

Validation


Need for validation: Simple, Garbage In- Garbage Out.

Where will you validate? Typically, the calculate button click event should have the following 3 steps.
1. Move form objects into variables
2. Processing or calculation
3. Move contents of output variable into form objects


Knowing that the computer executes code sequentially, where would you want to place the code that validates what the user keys in.
1.After you display the output to the user?
2.After Processing but before display the output to the user?
3.Before you start processing?

Thoughts? Comments?

Code Structure - Must Read


The following is a code snippet from the click event of the calculate button (Assignment 5-4). Please make sure your code has the following 3 steps. Note, The computer executes code sequentially, so these steps must be in the order specified.


1. Move form objects into variables ( otherwise your variables will contain nothing)

2. Processing (All of the calculations)

3. Move the output variable into form object. ( otherwise the labels will display nothing)


Const cIntSingle As Integer = 38I
Const cIntFamily As Integer = 58I
Const cintAncient As Integer = 27I
Dim intMonths As Integer
Dim decTotal As Decimal

'Move inputs from form into variables
intMonths = txtMonths.Text


'Processing

If Me.radSingle.Checked Then
decTotal = intSingle * intMonths
ElseIf Me.radFamily.Checked Then
decTotal = intFamily * intMonths
ElseIf Me.radAncient.Checked Then
decTotal = intAncient * intMonths
End If


'Move output to form objects
lblTotal.Text = decTotal.ToString("C")