user2568960
user2568960

Reputation: 65

Validate textbox with vb.net web forma

I need help to restrict my textbox to accept just numbers. I have another textbox event textchanged and in that condition I want to not allow user to write other characters than numbers. have implemented the maxlength but I can't validate to accpet just numbers. here is my condition that I want to implement in:

 Protected Sub txtIdType_TextChanged(sender As Object, e As EventArgs)
      Dim txtb As TextBox = CType(FormViewPerson.FindControl("txtIdType"), TextBox)
      Dim txtb1 As TextBox = CType(FormViewPerson.FindControl("TextBoxIDCode"), TextBox)

      If (txtb.Text = "Leternjoftimi" OrElse txtb.Text = "KosovoIDCard" OrElse txtb.Text = "Licna karta") Then
           txtb1.MaxLength = 10
      End If
 End Sub

Upvotes: 0

Views: 262

Answers (3)

user2568960
user2568960

Reputation: 65

I solved my problem using this function :

 For Each ch As Char In txt.Text
                If Not Char.IsDigit(ch) Then
                    txt.Text = ""
                    Exit Sub
                End If
            Next

Upvotes: 1

enb081
enb081

Reputation: 4061

You can add the validator from code behind. Try to do the following:

 Protected Sub txtIdType_TextChanged(sender As Object, e As EventArgs)
            Dim txtb As TextBox = CType(FormViewPerson.FindControl("txtIdType"), TextBox)
            Dim txtb1 As TextBox = CType(FormViewPerson.FindControl("TextBoxIDCode"), TextBox)

            If (txtb.Text = "Leternjoftimi" OrElse txtb.Text = "KosovoIDCard" OrElse txtb.Text = "Licna karta") Then

            txtb1.MaxLength = 10
            Dim validator As New RegularExpressionValidator()
            validator.ID = "validator" + New Random().[Next](100, 1000)
            validator.ControlToValidate = CType(FormViewPerson.FindControl("TextBoxIDCode"), TextBox).ID
            validator.ValidationExpression="^[0-9]*$"    
            FormViewPerson.Controls.Add(validator)

            End If

        End Sub

Suksese!

Upvotes: 1

HEEN
HEEN

Reputation: 4737

You can do this simply in aspx page, like below:-

<asp:TextBox ID="txtNumbers" runat="server" autocomplete="off" ValidationGroup="AddNew"></asp:TextBox>
<asp:RegularExpressionValidator ID="regNumbers" runat="server" ErrorMessage="Only numbers are allowed" ControlToValidate="txtNumbers" ValidationExpression="^[0-9]*$" ValidationGroup="AddNew"></asp:RegularExpressionValidator>

You don't need to use the code-behind for this. Hope this helps

Upvotes: 2

Related Questions