Required field, Email, Password and Phonenumber Validation in Visual Basic (VB.Net)

How to Validate the Email, Password, Phonenumber and make any input fields required or mandatory in Visual Basic(VB.Net)

In this Visual Basic tutorial, let’s perform some real-time examples to validate email, password, Phonenumber and required input fields in VB.

What is “Form Validation”?

Form validation is a “technical process where a web-form checks if the information provided by a user is correct or not.”

The form will either alert the user that they have done something wrong and need to correct something to proceed, or the form will be validated and the user will be able to continue with their process.

The validation of TextBox will be performed using the Validating event handler and the error message will be displayed using the ErrorProvider control in Windows Application (WinForms) using VB.Net.

Required field validation in VB

If the TextBox is empty an error message is set in the ErrorProvider control so with the help of Validating event handler,  the TextBox is validated for Empty and White space, and if the validation fails it shows the error message.

Private Sub txtName_Validating(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles txtName.Validating
If String.IsNullOrEmpty(txtName.Text.Trim) Then
epName.SetError(txtName, "Name is required.")
epName.SetError(txtName, String.Empty)
End If
End Sub

We can also use this code for giving the validation on the username or other required textboxes which we don’t want to be left empty.


Password Validation in VB

In this example, we can validate passwords with the help of Regular Expression.

If we want our password to be-

-must  contain at least 6 characters 
-It must contain at least one lower case letter,
One upper case letter,
One digit and one special character
-and Valid special characters are – @#$%^&+=

then (Passwords like ‘asWE$21@ut’, ‘RWE@#%345erO’ etc are the valid password entries according to the following code.)

Private Sub Button1_Click(ByVal Sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim MatchNumberPattern As String = "^.*(?=.{6,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$"
If TextBox2.Text.Trim <> "" Then
If Not Regex.IsMatch(TextBox2.Text, MatchNumberPattern) Then
MessageBox.Show("Invalid password !")
End If
End If
End Sub

The easy way is to use a regular expression to check the entered password is valid or not. For this the expression is "^.*(?=.{10,})(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=]).*$" .

And it will check if the entered password contains at least 6 characters (?=.{6,}) , at least 1 number(?=.*\d), 1 letter of lower case(?=.*[a-z]) , one letter of upper case (?=.*[A-Z]) and 1 character in the list (?=.*[@#$%^&+=]).

Email validation in VB

In this example we will see a regular expression for email validation,  this method calls the Regex.IsMatch(String, String) method and verify that the string conforms to a regular expression pattern.

Imports System.Text.RegularExpressions
Public Class Form1
Private Sub btnCheck_Click(sender As System.Object, e As System.EventArgs) Handles btnCheck.Click
Dim emailaddress = txtEmail.Text
Dim pattern As String = "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
Dim emailAddressMatch As Match = Regex.Match(emailaddress, pattern)
If emailAddressMatch.Success Then
'emailaddresscheck = True
MsgBox("Valid Email address", MsgBoxStyle.Information)
'emailaddresscheck = False
MsgBox("Incorrect email ID",MsgBoxStyle.Exclamation)
End If
End Sub
End Class

Phone number validation in VB

In VB.NET entitled “Validating a Phone Number”. We will validate a phone number with using System.Text.RegularExpressions namespace.

Import this namespace and put this at the topmost part of your code tab: Put this code for the Button1_Click. This will trigger to decide whether the inputted phone number is valid or not

Imports System.Text.RegularExpressions
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim phonenumber As New Regex("+\d{2}-\d{10}")
        If phonenumber.IsMatch(TextBox1.Text) Then
            MsgBox("Valid phone number!")
            MsgBox("Phnum Should 10 Digits and Format +91-xxxxxxxxxx")
        End If
    End Sub

This line of code ("+\d{2}-\d{5}-\d{5}") validate a phone number in + and the 2 number of country code +\d{2} and the next phrase will take 10 numbers that is-\d{10}.

If any number is in this format then application will show “valid phone number” otherwise it will show “Phnum Should 10 Digits and Format +91-xxxxxxxxxx” .

So in this way we can simply use Required field, password, email or phone number validation in VB.NET.