top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Create User Control To Validate Commonly Used Data Formats

+1 vote
222 views

Introduction

Many times we need to validate data entered in a TextBox for appropriate format such as e-mail, phone number and zip code. ASP.NET web controls along with ReqularExpression validator provide such validation mechanism. However, there is no such built-in way in Windows Forms. In this article I will explain how to create a windows user control that enhances System.Windows.Forms.TextBox control to validate commonly used data formats.

Data Formats and Regular Expressions

The System.Text.RegularExpressions namespace provides classes that allow you to use regular expressions. You can use its IsMatch property to check whether a certain pattern is present in the given expression or not.

Creating the user control

We will now write our own class that extends from the System.Windows.Forms.UserControl class. We will provide additional properties and validation logic in our implementation. Following code shows various members of the class:

Imports System.Text.RegularExpressions

Public Class ValidatingTextBox
    Inherits System.Windows.Forms.UserControl
    
    Private objExpr As Regex
    Private strExpr As String
    Private strErr As String
    Friend WithEvents TextBox1 As 
    System.Windows.Forms.TextBox
    Public Event ValidationFailed
    (ByVal sender As Object, ByVal e As EventArgs)

    Public Property ErrorMessage() As String
        Get
            Return strErr
        End Get
        Set(ByVal Value As String)
            strErr = Value
        End Set
    End Property

    Public ReadOnly Property IsValid() As Boolean
        Get
            If Not objExpr Is Nothing Then
                Return objExpr.IsMatch(TextBox1.Text)
            Else
                Return True
            End If
        End Get
    End Property

    Public Property ValidationExpression() As String
        Get
            Return strExpr
        End Get
        Set(ByVal Value As String)
            strExpr = Value
            objExpr = New Regex(strExpr)
        End Set
    End Property

    Private Sub TextBox1_Validated
    (ByVal sender As Object, ByVal e As System.EventArgs) 
    Handles TextBox1.Validated
        If Not Me.IsValid Then
            RaiseEvent ValidationFailed(Me, New EventArgs())
        End If
    End Sub

End Class    

Here, we created our own class with added three properties:

  • ErrorMessage: The string that will be displayed as error message in case validation fails.
  • IsValid: It is a read only property that tells whether the value contained in the TextBox is valid or not
  • ValidationExpression: This property sets a regular expression that will be used to validate the content of the TextBox.

The class also exposes an event called ValidationFailed that will be raised if content entered does not match with the pattern indicated by the regular expression.

Commonly used regular expressions

ASP.NET regular expression validator provides some built in regular expressions that validate things such as e-mail and zip code. We will now create a class that provides such expressions readily to use.

Public Class CommonValidationExpressions
    Public Shared Email As String = 
    "\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
    Public Shared URL As String = 
    "http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"
    Public Shared USPhone As String = 
    "((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}"
    Public Shared SSN As String = 
    "\d{3}-\d{2}-\d{4}"
    Public Shared ZIP As String = 
    "\d{5}(-\d{4})?"
    Public Shared DateMMDDYYYY As String = 
    "^\s*\d{1,2}(/|-)\d{1,2}\1(\d{4}|\d{2})\s*$"
    Public Shared IPAddress As String = 
    "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]
    [0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]
    |1[0-9][0-9]|[1-9][0-9]|[0-9])$"
End Class

We opted to create a class with shared members instead of an enumeration so that you can easily set the ValidationExpression property to one of these values.

Using ValidatingTextBox

In order to test our control we created a windows forms application and put our control on a form. We set validation expression to check e-mail address. You can run the application and test for various other regular expressions.

I hope you must have liked the article. See you soon.

posted Jan 7, 2017 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Introduction

Many times we need to validate user input for numeric, alphabetic and alphanumeric format. Windows forms do not have Maskedit box as in VB6. In this code sample we will see how to create your own custom control that inherits from the standard TextBox control and extends its functionality to validate numbers, alphabets and alphanumeric characters.

Requirements

The Basic requirements for the control are to

  • Allow numbers, alphabets and alphanumeric characters. The input can filtered based on the setting of "ValueType" property.
  • In case the "ValueType" property is set to "Num" - Allow entry for one decimal point only, Allow a minus sign, but only at the first position in the text box, Allow numbers in the range between "MinValue" and "MaxValue", if they are set.
  • Can make the field Mandatory. Can make the field Mandatory by setting property, default is False.

ValueType Property

The value type property is an enumeration (ValMode) with following values:

  • ValueType = AlphaNum, for Alphabet and Numerics
  • ValueType = Num, for only Numerics
  • ValueType = Alpha, for only Alphabet

Error Messages

We can have customized error message set via ErrorMessage property if this validation fails.

Checking for valid entry

The User input is validated/checked using the "KeyPress" event of the standard TextBox Control. The type of value (input) in the control is filtered using the Pre-defined value, which are provided by the Enumerator (Enum) "ValMode".

Changing focus color

Some times we have number of TextBox controls on the Win Form, and at times we can't find where the focus is, so we have added two properties which changes the color of the control when it receive and leave the focus. It is done by using the "Enter" and "Leave" events of the TextBox.

READ MORE
...