简体   繁体   English

使用vb.net Web格式验证文本框

[英]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. 已经实现了maxlength,但我无法验证仅接受数字。 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

You can do this simply in aspx page , like below:- 您可以简单地在aspx page执行此操作,如下所示:-

<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. 您无需为此使用code-behindcode-behind Hope this helps 希望这可以帮助

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! Suksese!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM