TextBox Validation

kingsonprisonic 4 Tallied Votes 1K Views Share

This module is for validating textboxes....

After using this module in your project you can simply validate all of your text boxes like

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AssignValidation(Me.TextBox1, ValidationType.Only_Digits)
        AssignValidation(Me.TextBox2, ValidationType.Only_Characters)
        AssignValidation(Me.TextBox3, ValidationType.No_Blank)
        AssignValidation(Me.TextBox4, ValidationType.Only_Email)
    End Sub
scarcella commented: very nicely written +3
ddanbe commented: Nice code! +14
Imports System.Text.RegularExpressions

Module Validator

    Public Enum ValidationType
        Only_Digits = 1
        Only_Characters = 2
        No_Blank = 3
        Only_Email = 4
    End Enum

    Public Sub AssignValidation(ByRef CTRL As TextBox, ByVal Validation_Type As ValidationType)
        Dim txt As TextBox = CTRL

        Select Case Validation_Type

            Case ValidationType.Only_Digits
                AddHandler txt.KeyPress, AddressOf ONUM_Leave

            Case ValidationType.Only_Characters
                AddHandler txt.KeyPress, AddressOf OCHAR_Leave

            Case ValidationType.No_Blank
                AddHandler txt.Leave, AddressOf NOBLANK_Leave

            Case ValidationType.Only_Email
                AddHandler txt.Leave, AddressOf Email_Leave

        End Select


    End Sub

    Public Sub ONUM_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        Dim txt As TextBox = sender
        If InStr("1234567890.", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(txt.Text, ".") > 0) Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub

    Public Sub OCHAR_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If InStr("1234567890!@#$%^&*()_+=-", e.KeyChar) > 0 Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub



    Public Sub NOBLANK_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim t As TextBox = sender

        If t.Text.Trim = "" Then
            MsgBox("This field Must be filled!")
            t.Focus()
        End If
    End Sub


    Public Sub Email_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim txtEmail_1 As TextBox = sender
        If txtEmail_1.Text <> "" Then
            Dim rex As Match = Regex.Match(Trim(txtEmail_1.Text), "^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,3})$", RegexOptions.IgnoreCase)
            If rex.Success = False Then
                MessageBox.Show("Please Enter a valid Email-Address 1", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
                txtEmail_1.BackColor = Color.Red
                txtEmail_1.Focus()
                Exit Sub
            Else
                txtEmail_1.BackColor = Color.White
            End If
        End If
    End Sub



End Module
scarcella 11 Senior Software Architect

This is some nice piece of code, thank you. It really helped alot with my project.

~ Marais

mie.ilani 0 Light Poster

thanks!

echo12 0 Newbie Poster

Thank you soooooooooooooo much, this helped me a lot in my project.

Icone -1 Junior Poster in Training

I'm new to this piece of code. It sounds very nice way of validating a textbox.

kplcjl 17 Junior Poster

I do have a question. In your regex expression you have [0-9a-zA-Z] sprinkled throughout. Since you also have ", RegexOptions.IgnoreCase" wouldn't [0-9a-z] serve just as well?
If it doesn't, why do you use IgnoreCase?

I might add, this might not work so well on the international front.
FYI Your no_blank validation could be applied to the first two textboxes as well

kplcjl 17 Junior Poster

I take it you don't want to allow clipboard copy on the key events?

san.ssj 12 Newbie Poster

[IMG]http://i45.tinypic.com/9zxbvt.png[/IMG]

getting this error :(
please help :S

san.ssj 12 Newbie Poster

^Sorry my bad found out. It was my mistake :S

pearl.kumar1 0 Light Poster

I can't get exactly where would i use this code in my module.Please help some simple example to use this code..
If i use this code, Error Statements are "'Module' statements can occur only at file or namespace level" .

pearl.kumar1 0 Light Poster

Sorry,It's My Fault..I'm not using Namespace in my module,this is first time,I resolve the error..TY

LuckyBhumkar 0 Newbie Poster

One of the easiest example of Validation. Just takes a minute to implement. Thanks buddy for this nice snippet.

Iamateur 0 Junior Poster in Training

Hey it seems to be nice code but can you please tell me this code is useful in which kinda projects?
To try out this code,should I open new project->new form->add few text boxes.
And in the coding section of the form ,write down this code?
Will it work out?
I am beginner.So asking so many questions:X
Will be waiting for reply.

ddanbe 2,724 Professional Procrastinator Featured Poster

@ Iamateur: This code is meaningless!
But if you have a program project, where you need a texbox to fill in only an email address, then this is super code to have!

Iamateur 0 Junior Poster in Training

ddanbe
Ok so this code is used to accept different email ids from users.
And for this only 1 text box to accept email-id is required?
Any more text boxes to display something is required?
Any changes to be made in the properties of text box?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.