0% found this document useful (0 votes)
8 views

Labactivity 13 Inputvalidationandexceptionhandling

The document provides instructions for a lab practical on input validation and exception handling. It describes creating a windows form application to validate user input using regular expressions and providing error messages. It also covers exception handling by adding a try/catch block to handle potential errors from dividing a number by zero.

Uploaded by

Aisyah Hanis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Labactivity 13 Inputvalidationandexceptionhandling

The document provides instructions for a lab practical on input validation and exception handling. It describes creating a windows form application to validate user input using regular expressions and providing error messages. It also covers exception handling by adding a try/catch block to handle potential errors from dividing a number by zero.

Uploaded by

Aisyah Hanis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Centre for Diploma Studies Page 1/7

Department of Information Technology Session 2023/2024


Lab Practical Title: Input Validation and Exception Semester 2
Handling

CENTRE FOR DIPLOMA STUDIES

MULTIMEDIA CONCEPT

LABORATORY INSTRUCTION SHEET

Course Code DAT 21103

INPUT VALIDATION AND


Lab Practical Title
EXCEPTION HANDLING

Lab Practical 13
Centre for Diploma Studies Page 2/7
Department of Information Technology Session 2023/2024
Lab Practical Title: Input Validation and Exception Semester 2
Handling

Learning Outcome(s)
At the end of this practical session, you should be able to:
1. Write a VB code for input validation
2. Write a code with exception handling application development.

Contextual Situation 13.1:

Create a windows application that makes use of Regular Expressions to determine


valid input.

Figure 7.9: Design of a form

Solution 13.1:
Step 1: Design a Form and Step 2: Set the Properties
i. Create a Windows VB.NET application and design the form to resemble Figure 7.9.
ii. Add a tooltip in your design

iii. Set the properties for all controls

Step 3: Write a program code


(a) Set a namespace
The Regular Expression's functionalities exist in a namespace, so let us add that
first:
' Regular Expressions Namespace
Imports System.Text.RegularExpressions
Centre for Diploma Studies Page 3/7
Department of Information Technology Session 2023/2024
Lab Practical Title: Input Validation and Exception Semester 2
Handling

(b) General Declarations for variables


Add the following variables inside Module Level Declarations section:

Private NameValid As Boolean 'Is Name Valid?


Private PhoneValid As Boolean 'Is Phone Number Valid?
Private EmailValid As Boolean 'Is Email Valid?
Private AgeValid As Boolean 'Is Age Valid?
Dim tt As New ToolTip With {.IsBalloon = True}

(c) Validating Names using an Leave event and Regex.Match() Method


A name doesn't generally contain weird symbols, and definitely not numbers.
Add the following inside your name Textbox's Leave event:

Private Sub txtName_Leave(ByVal sender As Object, ByVal e _


As System.EventArgs)_
Handles txtName.Leave

'If Not A Matching Format Entered


If Not String.IsNullOrEmpty(txtName.Text) Then

If Not Regex.Match(txtName.Text, "^[a-z]*$", _


RegexOptions.IgnoreCase).Success Then 'Only Letters
'Inform User
MessageBox.Show("Please Enter Alphabetic Characters Only!")

txtName.Focus() 'Return Focus


txtName.Clear() 'Clear TextBox

NameValid = False 'Boolean = False


Else

NameValid = True 'Everything Fine

End If
Else
tt.Show("Insert your name", txtName, New Point(0, -40), 4000)
txtName.Focus() 'Return Focus
End If

End Sub

(d) Validating Phone Numbers


Phone numbers usually follow some sort of format. This is because it becomes
more legible than just a normal set of numbers. People expect to enter a phone
number in a format similar to this: ###-#######.

'Function To Check Phone Number Validity


Public Function ValidatePhone(ByVal strPhoneNum As String) As Boolean

'Create Reg Exp Pattern


Dim strPhonePattern As String = "\d{3}-\d{7}"
Centre for Diploma Studies Page 4/7
Department of Information Technology Session 2023/2024
Lab Practical Title: Input Validation and Exception Semester 2
Handling
'Create Reg Ex Object
Dim rePhone As New Regex(strPhonePattern)

'Something Typed In
If Not String.IsNullOrEmpty(strPhoneNum) Then
'Check Validity
PhoneValid = rePhone.IsMatch(strPhoneNum)

End If

Return PhoneValid 'Return True / False

End Function

This function is later called inside the textbox's Leave event:


Private Sub txtTel_Leave(ByVal sender As Object, ByVal e
As System.EventArgs)_
Handles txtTel.Leave

If String.IsNullOrEmpty(txtTel.Text) = True Then


tt.Show("Insert your phone number",txtTel,New Point(0,-80), 2000)
txtTel.Focus() 'Return Focus
Else
ValidatePhone(txtTel.Text)
'Call Phone Validation Function
If PhoneValid = False Then
txtTel.Focus() 'Return Focus
txtTel.Clear() 'Clear Input
MessageBox.Show("Enter phone number in Correct Format!")

End If
End If
End Sub

(e) Validating Emails


Emails also follow a certain format. It is always username at sub domain dot
domain.

Private Sub ValidateEmail()

'Set Up Reg Exp Pattern To Allow Most Characters,


‘And No Special Characters
Dim reEmail As Regex = New Regex _
("([a-zA-Z0-9_\-\.]+)@" + _
"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)" + _
"|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})", _
RegexOptions.IgnoreCase _
Or RegexOptions.CultureInvariant _
Or RegexOptions.IgnorePatternWhitespace _
Or RegexOptions.Compiled)

'Check If Entered Email Is In Correct Format


Dim blnPossibleMatch As Boolean = reEmail.IsMatch(txtEmail.Text)

If blnPossibleMatch = False Then


Centre for Diploma Studies Page 5/7
Department of Information Technology Session 2023/2024
Lab Practical Title: Input Validation and Exception Semester 2
Handling

EmailValid = False 'Set Boolean Variable To False

MsgBox("Invalid Email Address!") 'Inform User

txtEmail.Clear() 'Clear Textbox


txtEmail.Focus() 'Set Focus To TextBox
Else
EmailValid = True 'Email is Perfect
End If

End Sub

Private Sub txtEmail_Leave(ByVal sender As Object, ByVal e


As System.EventArgs)_
Handles txtEmail.Leave

If String.IsNullOrEmpty(txtEmail.Text) = True Then


tt.Show("Insert your email address", txtEmail, New Point(0, -80), 3000)
txtEmail.Focus() 'Return Focus
Else
ValidateEmail() 'Check Email Validity
End If

End Sub

(f) Validating Age


Private Sub txtAge_Leave(ByVal sender As Object, ByVal e As
System.EventArgs)_
Handles txtAge.Leave

If String.IsNullOrEmpty(txtAge.Text) = True Then


tt.Show("Insert your age", txtAge, New Point(0, -40), 2000)
txtAge.Focus() 'Return Focus
Else
For Each ch As Char In txtAge.Text
If Not Char.IsDigit(ch) Then
AgeValid = False
txtAge.Focus()
txtAge.Clear()
MsgBox("Please Enter Valid Age Only")

Else
AgeValid = True
End If
Next
End If

End Sub

(g) Event procedure for btnSubmit


Private Sub btnSubmit_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnSubmit.Click

'Check If All Input Text Is Correct


If NameValid AndAlso PhoneValid AndAlso EmailValid AndAlso AgeValid Then
Centre for Diploma Studies Page 6/7
Department of Information Technology Session 2023/2024
Lab Practical Title: Input Validation and Exception Semester 2
Handling

'Yes It Is
MessageBox.Show("All data Submitted Correctly")

Else 'No It Is Not

MessageBox.Show("Check your Data!")

End If
End Sub

(h) Event procedure for btnCancel


Private Sub btnCancel_Click(sender As System.Object, e As System.EventArgs)_
Handles btnCancel.Click

'Create Temporary Control Variable


Dim tText As Control

'Loop Through All Controls On Form


For Each tText In Me.Controls

'Cheakc If Current Control Is A textBox


If TypeOf tText Is TextBox Then

tText.Text = String.Empty 'Clear Text

End If

Next tText

End Sub

Guided Task 13.2: Exception Handling

Contextual Situation 13.2:


Create a web application to calculate division of value 1 with a numbers. User will
input the number and click a button to perform the calculation. The result will display at
a Label. A design of the web form in the application shown as below.

2/ = Answer
Calculat

Solution 13.2:
Centre for Diploma Studies Page 7/7
Department of Information Technology Session 2023/2024
Lab Practical Title: Input Validation and Exception Semester 2
Handling
Step 1: Design a Form and Step 2: Set the properties for each object controls
i. Create a new web application project
ii. In a new web form, add the suitable objects and set its properties

Step 3: Write a program code


Click Event Procedure for a btnCalculate:
Double-click the button and add the following code to the Click event of the button:
lblAnswer.Text = 2 \ txtNumber.Text

Step 4: Run the program and fix the error (if occurred)
i. Run using Start button available at the Microsoft Visual Studio tool bar
ii. Key in the number 0 at the textbox through textbox and click button ‘Calculate’
iii. What an error occurred?
iv. Modify your event procedure by add exception handling structure as below:

Try
lblAnswer.Text = 2 \ txtNumber.Text 'Code to be executed

Catch ex As Exception
MessageBox.Show(ex.ToString())'Error resolution code
Finally
MessageBox.Show("finally block executed") 'Cleanup code
End Try

v. Return your application


vi. Key in the number 0 at the textbox through textbox and click button ‘Calculate’
vii. Did you see any difference?

You might also like