Pages

Search This Blog

Friday, 27 January 2012

VB.NET Code for text box validation

If you wish to accept only characters (A-Z) in a textbox the following code does that stuff:


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim flag As Integer
        'check for validation/0-no error;1-error i/p
        flag = validatetext(TextBox1.Text)
        If flag = 0 Then
            MsgBox("Input is correct")
        Else
            MsgBox("TextBox Contains invalid characters")
        End If
End Sub

validatetext is a function which tests whether the text box contains only characters (A-Z). If the input contains only alphabets the function validatetext returns 0 else it returns 1. The following is the code for method validatetext



Public Function validatetext(ByVal input As String) As Integer
        Dim iLen As Integer
        Dim i As Integer
        Dim sChar As String
        iLen = Len(input)
        If iLen > 0 Then
            For i = 1 To iLen
                sChar = Mid(input, i, 1)
                If Not sChar Like "[A-Za-z-]" Then Return 1
            Next
        Else
            Return 0
        End If
End Function

No comments:

Post a Comment