Sei sulla pagina 1di 16

User Input Validation

Visual Basic .NET

Validation
Validation refers to ensuring entered data is well, valid.
Validation helps avoid bugs by filtering out invalid data to
get in to the program flow.

Basic Validation Process

Format test - This test determines if the entered string is in the


correct format.

Type test - This test checks if the input is the correct type. For
example: Integers of dates that do not need conversion afterwards.

Permitted Character test - This test ensure that no illegal


characters are entered. For example: If a user is supposed to enter
a name, numbers and some special symbols must not be allowed.

Range test - This tests checks to see if entered values are within a
specified range. For example : If you are only supposed to type in
50 characters, you must not be able to enter more than fifty.

Regular Expressions

Provide a powerful, flexible, and efficient method


for processing text.

Enables you to quickly parse large amounts of text


to find specific character patterns;

To validate text to ensure that it matches a


predefined pattern (such as an e-mail address);

Regular Expressions

To extract, edit, replace, or delete text substrings;


and to add the extracted strings to a collection in
order to generate a report.

RegEx Example - Replacing


SubString
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "(Mr\.? |Mrs\.? |Miss |Ms\.? )"
Dim names() As String = { "Mr. Henry Hunt", "Ms. Sara Samuels",
_
"Abraham Adams", "Ms. Nicole Norris" }
For Each name As String In names
Console.WriteLine(Regex.Replace(name, pattern, String.Empty))
Next
End Sub
End Module
' The example displays the following output:
' Henry Hunt
' Sara Samuels
' Abraham Adams
' Nicole Norris

RegEx - Identifying
Duplicate Words
Imports System.Text.RegularExpressions
Module modMain
Public Sub Main()
Dim pattern As String = "\b(\w+?)\s\1\b"
Dim input As String = "This this is a nice day. What about this?
This tastes good. I saw a a dog."
For Each match As Match In Regex.Matches(input, pattern,
RegexOptions.IgnoreCase)
Console.WriteLine("{0} (duplicates '{1}') at position {2}", _
match.Value, match.Groups(1).Value,
match.Index)
Next
End Sub
End Module
' The example displays the following output:
' This this (duplicates 'This)' at position 0
' a a (duplicates 'a)' at position 66

RegEx
The regular expression pattern \b(\w+?)\s\1\b can be interpreted as
follows:
\b
Start at a word boundary.
(\w+?)
Match one or more word characters, but as few characters as possible.
Together, they form a group that can be referred to as \1.
\s
Match a white-space character.
\1
Match the substring that is equal to the group named \1.
\b
Match a word boundary.

RegEx Methods

The Regex.Matches method is called with regular


expression options set to
RegexOptions.IgnoreCase. Therefore, the match
operation is case-insensitive, and the example
identifies the substring "This this" as a duplication.

Note that the input string includes the substring


"this? This". However, because of the intervening
punctuation mark, it is not identified as a
duplication.

Guided Example

Start Visual Studio and create a Desktop VB.NET


application and design the form to resemble this
figure.

Example
Imports System.Text.RegularExpressions ' Regular Expressions Namespace
Private
Private
Private
Private

NameValid As Boolean 'Is Name Valid?


SurnameValid As Boolean 'Is Surname Valid?
PhoneValid As Boolean 'Is Phone Number Valid?
EmailValid As Boolean 'Is Email Valid?

Private Sub txtName_Leave(sender As Object, e As System.EventArgs) Handles


txtName.Leave
'If Not A Matching Format Entered
If Not Regex.Match(txtName.Text, "^[a-z]*$",
RegexOptions.IgnoreCase).Success Then 'Only Letters

MessageBox.Show("Please Enter Alphabetic Characters Only!") 'Inform


User

txtName.Focus() 'Return Focus


txtName.Clear() 'Clear TextBox

NameValid = False 'Boolean = False


Else

NameValid = True 'Everything Fine

End If

End Sub

Private Sub txtSurname_Leave(sender As Object, e As System.EventArgs) Handles txtSurname.Leave


'Create A Pattern For Surname
Dim strSurname As String = "^[a-zA-Z\s]+$"

Dim reSurname As New Regex(strSurname) 'Attach Pattern To Surname Textbox

'Not A Match
If Not reSurname.IsMatch(txtSurname.Text) Then

MessageBox.Show("Please Enter Alphabetic Characters Only!")

txtName.Focus()

txtName.Clear()

SurnameValid = False

Else

SurnameValid = True

End If

End Sub

'Function To Check Phone Number Validity


Public Function ValidatePhone(ByVal strPhoneNum As String) As Boolean

''Create Reg Exp Pattern


Dim strPhonePattern As String = "^[1-9]\d{2}-[1-9]\d{2}-\d{4}$"

'Create Reg Ex Object


Dim rePhone As New Regex(strPhonePattern)

'Something Typed In
If Not String.IsNullOrEmpty(strPhoneNum) Then

PhoneValid = rePhone.IsMatch(strPhoneNum) 'Check Validity

Else

PhoneValid = False 'Not Valid / Empty

End If

Return PhoneValid 'Return True / False

End Function
Private Sub txtTel_LostFocus(sender As Object, e As System.EventArgs) Handles txtTel.LostFocus

If Not ValidatePhone(txtTel.Text) Then 'Call Phone Validation Function

MessageBox.Show("Please Enter Phone Number In Correct Format!")

txtTel.Clear() 'Clear Input


txtTel.Focus() 'Return Focus

End If

End Sub

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 _
)

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

If blnPossibleMatch Then

'Check If Entered Email Is In Correct Format


If Not txtEmail.Text.Equals(reEmail.Match(txtEmail.Text).ToString) Then

MessageBox.Show("Invalid Email Address!")

Else

EmailValid = True 'Email is Perfect

End If

Else 'Not A Match To Pattern

EmailValid = False 'Set Boolean Variable To False

MessageBox.Show("Invalid Email Address!") 'Inform User

txtEmail.Clear() 'Clear Textbox

txtEmail.Focus() 'Set Focus To TextBox

End If

End Sub
Private Sub txtEmail_LostFocus(sender As Object, e As System.EventArgs) Handles txtEmail.LostFocus

ValidateEmail() 'Check Email Validity

End Sub

References:

MSDN

Code guru

Potrebbero piacerti anche