Click here to Skip to main content
15,889,216 members
Articles / Programming Languages / Visual Basic
Article

Ready to use custom textbox with validation properties

Rate me:
Please Sign up or sign in to vote.
4.27/5 (17 votes)
10 Mar 20052 min read 83.1K   883   24   6
Use of this control will eliminate various common validation issues in a form.

Image 1

Introduction

glblControl Textbox

The use of this control eliminates various common validation issues in a form. Properties available with this control are:

  • Required: Sets the field as required for validation. Required textbox’s background color will be changed to Old Lace.
  • ShowErrorIcon: It is either True or False, it shows a flashing icon. If the required property is set to true and the field is left blank, it will show a red flashing icon. If invalid value is entered, it will flash a yellowish icon.
  • ValidationMode: Sets the validation mode to use. They are the following:
    • None
    • Any value
    • Valid characters e.g. “$1234567890.,”
    • Invalid characters e.g. “@#$%’”^&*”
    • Letters
    • Only alphabets (includes “ , ; . ”)
    • Numbers
    • Only numbers (includes “.”)
  • Textbox (valid/invalid sharacters): Sets this property with valid/invalid characters as per the ValidationMode property.

Events handled

  • TextChanged
  • KeyPress
  • Validating
  • Validated
  • Enter
  • Leave

Limitations: It can check for the form level required property for only those controls where Container level is less than or equal to 4. I.e., if the textbox is in Panel4, under Panel3, under Panel2, under Panel1 under FORM, the form level required property will not be checked when exiting form without any input in the textbox.

Pointing to a yellowish or red error icon will show you tips as to what has gone wrong. The only required code in the form is as follows:

On the OK button:

VB
If glblControls.TextBox.requiredFieldsCheck(Me) = True Then
    MsgBox("OK!", MsgBoxStyle.Information, Me.Text)
    Me.Close()
Else
    MsgBox("There are required fields in the form!", 
       MsgBoxStyle.Exclamation, Me.Text)
End If

On the Cancel button:

VB
glblControls.TextBox.cancelrequiredFieldsCheck(Me)
Me.Close()

glblControl Masked Textbox

This is a very easy to use Masked Textbox for fixed length strings like phone numbers, social security, driver license, etc.

  • The "#" character in the mask is used for digit only.
  • The "&" character accepts letters only.
  • The "!" character accepts a letter or digit.
  • You can use any mask symbol, letter and digit other than # & and !.

E.g. ###-&!/&&(###) ###-!!!! &&XXX##Z12&&&

Using the component

Set the mask property with any combination of characters. At run time, you can read the unformatted Text property to read only the user input. The Text property returns the formatted string.

Image 2

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey12-Mar-12 22:26
professionalManoj Kumar Choubey12-Mar-12 22:26 
GeneralMask Pin
kiquenet.com6-Aug-08 2:07
professionalkiquenet.com6-Aug-08 2:07 
GeneralCorrect number of points in a numeric format Pin
alavitiricchiarazio2-Nov-05 3:17
alavitiricchiarazio2-Nov-05 3:17 
GeneralRe: Correct number of points in a numeric format [modified] Pin
BarryGSumpter16-Dec-06 11:43
BarryGSumpter16-Dec-06 11:43 
GeneralI had made some change Pin
aiway27-Mar-05 19:38
aiway27-Mar-05 19:38 
Thanks,your code,it's short and powerful,in use numbers and letters.But In my contry(Taiwan),If you input Chinese Word,that will be error,so I get a change as blow:(and thanks again)

Imports System.Windows.Forms
Imports System.Text

Public Class MaskedTextBox
Inherits System.Windows.Forms.TextBox

Private mstrMask As String = ""
Private mParams() As Char = {CChar("#"), CChar("&"), CChar("!"), CChar("@")}
Private bolHasMask As Boolean


#Region " Component Designer generated code "

Public Sub New(ByVal Container As System.ComponentModel.IContainer)
MyClass.New()

Container.Add(Me)
End Sub

Public Sub New()
MyBase.New()

'This call is required by the Component Designer.
InitializeComponent()

'Add any initialization after the InitializeComponent() call

End Sub

'Component overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub

'Required by the Component Designer
Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Component Designer
'It can be modified using the Component Designer.
'Do not modify it using the code editor.
<system.diagnostics.debuggerstepthrough()> Private Sub InitializeComponent()
components = New System.ComponentModel.Container
End Sub

#End Region

#Region "Attribute.."

#Region "property...."

Public ReadOnly Property UnformatedText() As String
Get
Dim i As Integer
Dim strText As String = ""

For i = 0 To mstrMask.Length - 1
If Array.IndexOf(mParams, mstrMask.Chars(i)) > -1 AndAlso Me.Text.Chars(i) <> "_" Then

strText += Me.Text.Chars(i)

End If
Next

Return strText

End Get
End Property

Public ReadOnly Property ValueText() As String
Get
Dim i As Integer
Dim strText As String = ""
For i = 0 To mstrMask.Length - 1
If Char.IsDigit(Me.Text.Chars(i)) OrElse Me.Text.Chars(i) = "."c Then
strText += Me.Text.Chars(i)
End If
Next
Return strText

End Get
End Property


Public Property Mask() As String

Get
Return (mstrMask)

End Get

Set(ByVal Value As String)

'Use # for Digit only
'Use & for Letter only
'Use ! for Letter or Digit
'Use @ for Letter or Digit or Chinese word
mstrMask = Value
Me.Text = mstrMask
Me.Text = Me.Text.Replace("#", "_").Replace("&", "_").Replace("!", "_").Replace("@", "_")

If Me.Text.Length > 0 Then
bolHasMask = True
Me.ContextMenu = New System.Windows.Forms.ContextMenu

Else
bolHasMask = False
Me.ContextMenu = MyBase.ContextMenu
End If

If Array.IndexOf(mParams, "@") > -1 Then

End If
End Set
End Property



#End Region 'end property...

#End Region 'end Attribute...



#Region "Method..."

Protected Overrides Sub OnKeyDown(ByVal e As System.Windows.Forms.KeyEventArgs)
'Original cursor position
Dim intSelStart As Integer = Me.SelectionStart
'In case of a selection, delete text to this position
Dim intDelTo As Integer = intSelStart + Me.SelectionLength
Dim i As Integer

If intSelStart > 0 And intDelTo < intSelStart Then
intSelStart -= 1
End If

'When Press Delete Key
If e.KeyCode = Keys.Delete And bolHasMask = True Then
e.Handled = True
For i = intSelStart To intDelTo
If Array.IndexOf(mParams, mstrMask.Chars(i)) > -1 Then
Me.Text = Me.Text.Remove(i, 1).Insert(i, "_")
End If
Next
Me.SelectionStart = intSelStart
Me.SelectionLength = 0
End If

End Sub

Protected Overrides Sub OnKeyPress(ByVal e As System.Windows.Forms.KeyPressEventArgs)
'key pressed
Dim chrKeyPressed As Char = e.KeyChar
'Original cursor position
Dim intSelStart As Integer = Me.SelectionStart
'In case of a selection, delete text to this position
Dim intDelTo As Integer = Me.SelectionStart + Me.SelectionLength - 1

Dim strText As String = Me.Text

'Used to avoid deletion of the selection when an invalid key is pressed
Dim bolDelete As Boolean = False

Dim i, j As Integer


'Try

e.Handled = True

If chrKeyPressed = ControlChars.Back And bolHasMask = True Then
bolDelete = True
If intSelStart > 0 And intDelTo < intSelStart Then
intSelStart -= 1
End If
ElseIf AscW(chrKeyPressed) = Keys.Space Then
bolDelete = True
If intSelStart >= 0 And intDelTo < intSelStart Then
intSelStart += 1
End If
ElseIf bolHasMask = False Then
e.Handled = False
Exit Sub
End If




'Find the Next Insertion point
For i = Me.SelectionStart To mstrMask.Length - 1

'Test for # or & ,this for only asc code(0~128),not for unicode(ex.asia code is can not use it)
If mstrMask.Chars(i) = "#" AndAlso Char.IsDigit(chrKeyPressed) AndAlso AscW(chrKeyPressed) < 255 _
OrElse mstrMask.Chars(i) = "&" AndAlso Char.IsLetter(chrKeyPressed) AndAlso AscW(chrKeyPressed) < 255 _
OrElse mstrMask.Chars(i) = "!" AndAlso Char.IsLetterOrDigit(chrKeyPressed) AndAlso AscW(chrKeyPressed) < 255 _
OrElse mstrMask.Chars(i) = "@" AndAlso Char.IsLetterOrDigit(chrKeyPressed) Then

j = i
strText = strText.Remove(i, 1).Insert(i, chrKeyPressed)
intSelStart = i + 1
bolDelete = True

End If


'Prevent looping unitl the next available match when mixing # & ! on the same mask
If Array.IndexOf(mParams, mstrMask.Chars(i)) > -1 Then
Exit For
End If

Next

'Delete remaining chars from selection or previous char if backspace
If bolDelete Then

For i = intSelStart To intDelTo

If Array.IndexOf(mParams, mstrMask.Chars(i)) > -1 Then
strText = strText.Remove(i, 1).Insert(i, "_")
End If
Next

Me.Text = strText

Me.SelectionStart = intSelStart
Me.SelectionLength = 0

End If

'for Taiwain's word(or asia word)
If mstrMask.Chars(j) = "@" AndAlso AscW(chrKeyPressed) > 255 Then
strText = strText.Remove(j, 1)
intSelStart = j
Me.Text = strText

Me.SelectionStart = intSelStart
Me.SelectionLength = 0

End If


'Catch err As System.Exception
' Me.Text = mstrMask
' Me.Text = Me.Text.Replace("#", "_").Replace("&", "_").Replace("!", "_")
'End Try
End Sub




Protected Overrides Function ProcessKeyEventArgs(ByRef m As System.Windows.Forms.Message) As Boolean
Dim intkeycode As IntPtr
intkeycode = m.WParam
If Array.IndexOf(mstrMask.ToCharArray, "@"c) = -1 AndAlso intkeycode.ToInt32 > 255 AndAlso bolHasMask = True Then
ProcessKeyEventArgs = True

Else

ProcessKeyEventArgs = MyBase.ProcessKeyEventArgs(m)
End If
End Function
#End Region 'End of Method....


End Class
GeneralNice! About Formatting Dates Pin
Bill Gerold18-Mar-05 3:27
Bill Gerold18-Mar-05 3:27 

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.