Click here to Skip to main content
15,885,278 members
Articles / Multimedia / GDI+
Article

Dynamic validation with Regular expression and ErrorProvider

Rate me:
Please Sign up or sign in to vote.
4.00/5 (4 votes)
3 Oct 2008CPOL3 min read 42.9K   369   15   6
in this Article we following how to dynamic validation data with defind validation type and use of regular expression
Snapshot1.GIF

Introduction

Perhaps it’s happening for you when receive data from users in forms, you need to filter and validation some edit controls,these data to prevent enter implausibility data. For instance fields of age: in these field user enter character such as "a" You forced to control the data of this field, when insert data or in key_press() event.

Background

Now you imagine you have a form and this form include 10 number fields, 5 string fields and 5 fields that fill them it's forced for user
Therefore we need to control many events that are not logical.

Using the Code

We need some methods about validation for the purpose of to be able have a class for control validation. For instance: we have need to 3 data type for validation. if we create components for validation ,now you need to edit and customize the component for your projects and is not good event so we use of class and define some methods base of your needs.

  • Unknow
  • NotNull
  • Numeric
  • Alphabet
  • Range

For define validation methods using Enum type

VB.NET
Public Enum ValidationType as byte
          UnKnow = 0
          NotNull = 1
          Numeric = 2
          Alphabet = 4
          Range = 8
End Num 

Now we needs define some object that response to receive data.
The object is called Errorprovides is your authorization at .NET 2005 that by using it you can handle the define data entry's. the way of implement this class.

VB.NET
 Public Class Shell_Validator
 ' generated by Ardavan Sharifi
 Shared Ep As ErrorProvider
 Public Enum ValidationType As Byte
      UnKnow = 0
      NotNull = 1
      Numeric = 2
      Alphabet = 4
      Range = 8
 End Enum
 Sub New()

 End Sub
 Public Overloads Shared Sub ValidTextbox_
(ByVal vType As ValidationType, ByVal Ctl As Control)
      Ep = New ErrorProvider(Ctl.FindForm)
      If vType > 0 Then
            Ctl.CausesValidation = True
            Ctl.AccessibleDescription = CType(vType, Byte)
            If (vType And 1) <> 0 Then
                 If Ctl.Tag = vbNullString Then
                      Ctl.Tag = 0 '+1 is valid length
                 End If
            End If
            AddHandler Ctl.GotFocus, AddressOf _Ctl_GotFocus
            AddHandler Ctl.Validating, AddressOf _Ctl_Validating
            ' have Numeric value So need to control event's
            If (vType And 2) <> 0 Then
                 AddHandler Ctl.KeyPress, AddressOf _Ctl_KeyPress
            End If
      End If
 End Sub
 Public Overloads Shared Sub ValidTextbox_
(ByVal Ctl As Control, ByVal minRage As Int32, ByVal MaxRange As Int32, _
          Optional ByVal vType As ValidationType = ValidationType.Range)
      If vType > 0 Then
            Ctl.CausesValidation = True
            Ctl.AccessibleDescription = CType(vType, Byte)
            If (vType And 1) <> 0 Then
                 If Ctl.Tag = vbNullString Then
                      Ctl.Tag = "0," & minRage & "," & MaxRange    ' for find range
                 Else
                      Ctl.Tag &= "," & minRage & "," & MaxRange
                 End If
            Else
                 Ctl.Tag = "-1," & minRage & "," & MaxRange
            End If
            AddHandler Ctl.Validating, AddressOf _Ctl_Validating
            AddHandler Ctl.GotFocus, AddressOf _Ctl_GotFocus 'for show error label
            ' have Numeric value So need to control event's
       If (vType And 2) <> 0 Then
                 AddHandler Ctl.KeyPress, AddressOf _Ctl_KeyPress
            End If
      End If
 End Sub
 Private Shared Sub _Ctl_GotFocus_
(ByVal sender As Object, ByVal e As System.EventArgs)
      Dim Ctl As Control
      Ctl = CType(sender, Control)
      If Len(Ep.GetError(Ctl)) > 0 Then
            'so has error
            Dim Lblvalidation As New Label
            Lblvalidation.Name = "valid_" & Ctl.Name
            Lblvalidation.Left = Ctl.Left + Ctl.Width + 18
            Lblvalidation.Top = Ctl.Top + 4
            Lblvalidation.Text = Ep.GetError(Ctl)
            Lblvalidation.Width = Lblvalidation.Text.Length * 5.8
            Lblvalidation.BackColor = Color.SkyBlue
            Lblvalidation.BorderStyle = BorderStyle.FixedSingle
            Lblvalidation.Height = 15
            Lblvalidation.ForeColor = Color.Red
            Ctl.FindForm.Controls.RemoveByKey("valid_" & Ctl.Name)
            Ctl.FindForm.Controls.Add(Lblvalidation)
      End If

 End Sub
 Private Shared Sub _Ctl_Validating(ByVal sender As Object, _
    ByVal e As System.ComponentModel.CancelEventArgs)
      Dim Vtype As ValidationType
      Vtype = Byte.Parse(CType(sender, Control).AccessibleDescription)
      Dim MyTag() As String
      MyTag = Split(CType(sender, Control).Tag, ",")
      If (Vtype And ValidationType.NotNull) <> 0 Then     ' Not null value
            Dim ValidLength As Integer = Int32.Parse(MyTag(0)) + 1
            If CType(sender, Control).Text.Length < ValidLength Then
                 GoError(sender, "Required!")
                 e.Cancel = True
                 Exit Sub
            Else
                 ClearError(sender)
                 e.Cancel = False
            End If
      End If
      If (Vtype And ValidationType.Numeric) <> 0 Then     'Numeric Type
            If Not isChecker(CType(sender, Control).Text, 1) Then
                 GoError(sender, "Please Insert number value!")
                 e.Cancel = True
            Else
                 ClearError(sender)
            End If
      ElseIf (Vtype = ValidationType.Alphabet) Or (Vtype = _
    ValidationType.Alphabet + ValidationType.NotNull) Then    _
                              'Alphabet or Alphabet And Not Null
            If Not isChecker(CType(sender, Control).Text, 0) Then
                 GoError(sender, "Please Insert letter!")
                 e.Cancel = True
            Else
                 ClearError(sender)
            End If
      ElseIf (Vtype = 6) Then 'Alphabet & Number
            If Not isChecker(CType(sender, Control).Text, 2) Then
                 GoError(sender, "Please Insert number or Letter value!")
                 e.Cancel = True
            Else
                 ClearError(sender)
            End If
      End If
      If (Vtype And 8) <> 0 Then
            Dim Vv As Int64 = 0
            If Int64.TryParse(CType(sender, Control).Text, Vv) = False Then
                 GoError(sender, "Please Insert Number value!")
                 e.Cancel = True
            Else
                 If (Vv <= Convert.ToInt64(MyTag(1))) Or (Vv >= _
                Convert.ToInt64(MyTag(2))) Then
                      GoError(sender, "Please Insert Number in " & _
                MyTag(1) & " And " & MyTag(2) & " !")
                      e.Cancel = True
                 Else
                      ClearError(sender)
                 End If
            End If
      End If
 End Sub

How to use Regular expression in validation

Here we have a function for checking entered data:

VB.NET
isChecker(ByVal MyStr As String, ByVal chktype As Byte) 

In this functuin you can use regex with define patterns. so you need some one.

VB.NET
readonly property(entry) as boolean

For define regular expression you can using this example: this function return validation of entry between 0 and 127.

VB.NET
Public ReadOnly Property isinRang(ByVal entry As String) As Boolean
       Get
     Return New Regex("^(0?[0-9]?[0-9]|1[0-1][0-9]|12[0-7])$", _
       RegularExpressions.RegexOptions.IgnoreCase).IsMatch(entry)
       End Get
   End Property

This function return validation of entry is number or alphabet.

VB.NET
Public ReadOnly Property IsAlphaNumeric(ByVal entry As String) As Boolean
    Dim c As New Regex("[^a-zA-Z0-9]").IsMatch(entry)
End Function

More Examples

Match a number between 0 and 255 : ^([01][0-9][0-9]|2[0-4][0-9]|25[0-5])$

Match a number between 000 and 255 : ^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$

Match a number between 0 and 127 : ^(0?[0-9]?[0-9]|1[0-1][0-9]|12[0-7])$

For more information about regular expression i suggest you to look at regular expressions and read this article use of Regular Expressions. now you can replace your function with section of isChecker function, I use of char's function.

If you like to use of regex on validation class you can refuse to entrying.

Optimized Code

In Page_Load(), just call validation function for objects:

VB.NET
ValidTextbox(ValidationType.NotNull, TextBox1)
ValidTextbox(ValidationType.Numeric, TextBox2)
ValidTextbox(3, TextBox3) ' Numeric And Not Null
ValidTextbox(ValidationType.Alphabet, TextBox4) ' Alphabet
ValidTextbox(ValidationType.UnKnow, TextBox5)    ' Free Format
ValidTextbox(TextBox6, 18, 60, 9)    ' Range Type
ValidTextbox(5, TextBox7) 'Alphabet And Not Null
ValidTextbox(ValidationType.Alphabet, Me.ComboBox1)    ' Only Alphabet

You can define different type of validation about your application with using this manner. And you can use tooltip object or another objects. when you are using Errorprovider and this class and You may also want to customize the generated code to fit your own needs.

Finally you can check the validation form by call ValidateChildren():

VB.NET
If ValidateChildren() = True Then
  MsgBox("Your information approved !!!", MsgBoxStyle.Information)
End If

Attention

Do not forget to notice to the following item if you are using regex class in you project

VB.NET
imports System.Text.RegularExpressions

In this article all of the focus is on validating event there fore this event is important for us and we must implementing dynamic. Also you can use of property's tag for controlling the number of authorized character. In Page_Load event calling base function for validation. Now in during validate for processing data we use of this function. After implement this methods you can be sure about enter data and validation.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Iran (Islamic Republic of) Iran (Islamic Republic of)
Software Developer

Comments and Discussions

 
GeneralLike this a lot but.... Pin
michaeltaylor12-Sep-08 3:39
michaeltaylor12-Sep-08 3:39 
GeneralRe: Like this a lot but.... Pin
Ardavan Sharifi12-Sep-08 20:10
Ardavan Sharifi12-Sep-08 20:10 
GeneralRe: Like this a lot but.... Pin
michaeltaylor15-Sep-08 7:10
michaeltaylor15-Sep-08 7:10 
GeneralRe: Like this a lot but.... Pin
Ardavan Sharifi15-Sep-08 21:27
Ardavan Sharifi15-Sep-08 21:27 
GeneralASP.NET like validation ... Pin
Vahid_N3-Sep-08 23:35
Vahid_N3-Sep-08 23:35 
GeneralRe: ASP.NET like validation ... Pin
Ardavan Sharifi3-Sep-08 23:58
Ardavan Sharifi3-Sep-08 23:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.