vb.net 文本框验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4165945/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Text box validation
提问by Harish
I am using many text boxes in a form. How do i validate them, In certain text boxes I have to use only text and in some I have to use only numbers. Is using ASCII is a right method or is there any easier method to do this. If so please let me know the coding.
我在表单中使用了许多文本框。我如何验证它们,在某些文本框中,我必须只使用文本,而在某些文本框中,我必须只使用数字。使用 ASCII 是一种正确的方法还是有任何更简单的方法可以做到这一点。如果是这样,请让我知道编码。
采纳答案by Schenz
Wow, this can be a very broad topic...
哇,这可能是一个非常广泛的话题......
For numeric textboxes, you should probably restrict input during KeyPress event:
对于数字文本框,您可能应该在 KeyPress 事件期间限制输入:
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
NOTE: This code sample is assuming WinForms, different approach must be used for web...
注意:此代码示例假设使用 WinForms,必须对 Web 使用不同的方法...
Regardless of the plat form, you should look into the validation controls offered by the framework, and that will allow you to validate that there is indeed input, values are in a specified range, and also using regex write more complicated validation rules.
无论平台如何,您都应该查看框架提供的验证控件,这将允许您验证确实存在输入、值是否在指定范围内,并且还可以使用正则表达式编写更复杂的验证规则。
回答by Konrad Rudolph
Above all other, don't annoy the user. If I'm typing some text and the application prevents that (regardless of how it does that), I'm rightfully pissed off.
最重要的是,不要惹恼用户。如果我正在输入一些文本而应用程序阻止了它(不管它是如何做到的),我理所当然地生气。
There are multiple values to handle this:
有多个值可以处理此问题:
Use a
NumericUpDown
or aSlider
control instead of a text box for numeric values (in other words: use the correct control instead of a general-purpose control).Allow (more or less) arbitrary input and try to parse the user input in a meaningful way. For example, entering “
+33 (0) 6 12-34-56
” is an entirely meaningful format for a phone number in France. An application should allow that, and try to parse it correctly.Granted, this is the hardest way, but it provides the best user experience.
Use the
Validating
event to validate input. This is automatically triggered whenever the user leavesthe input control, i.e. when they have finishedtheir input, and a validation will not annoy the user.The MSDN documentation of the event gives an example of how this event is used correctly.
对数值使用 a
NumericUpDown
或 aSlider
控件而不是文本框(换句话说:使用正确的控件而不是通用控件)。允许(或多或少)任意输入并尝试以有意义的方式解析用户输入。例如,对于
+33 (0) 6 12-34-56
法国的电话号码,输入“ ”是一种完全有意义的格式。应用程序应该允许这样做,并尝试正确解析它。诚然,这是最困难的方式,但它提供了最好的用户体验。
使用
Validating
事件来验证输入。每当用户离开输入控件时,即当他们完成输入时,这都会自动触发,并且验证不会惹恼用户。该事件的 MSDN 文档给出了如何正确使用该事件的示例。
But do notuse the KeyPress
or TextChanged
events to do validation. The first will disturb the users when entering text. The second will alsoannoy them when they try to paste text from somewhere else. Imagine the following: I am trying to copy an number from a website. Unfortunately, the text I have copied includes something else, too, e.g. “eggs: 14.33 EUR
” instead of just “14.33
”.
但是不要使用KeyPress
orTextChanged
事件来做验证。第一个会在输入文本时打扰用户。第二个会也惹恼了他们,当他们尝试从别的地方粘贴文本。想象一下:我试图从网站复制一个数字。不幸的是,我复制的文本也包含其他内容,例如“ eggs: 14.33 EUR
”而不仅仅是“ 14.33
”。
Now, the application mustgive me the chance to paste and correct the text. If I am not allowed to do that, the application is a UX failure. If the application uses the TextChanged
event to prevent my pasting this text, I don't get the chance to delete the offending text.
现在,应用程序必须让我有机会粘贴和更正文本。如果我不被允许这样做,则该应用程序是 UX 故障。如果应用程序使用该TextChanged
事件来阻止我粘贴此文本,则我没有机会删除有问题的文本。
回答by Chip Hunt
Text only limited to 40 characters:
文本仅限于 40 个字符:
<asp:RegularExpressionValidator ID="regexpText" runat="server"
ErrorMessage="Text only!"
ControlToValidate="txtName"
ValidationExpression="^[a-zA-Z]{1,40}$" />
Only Numbers:
只有数字:
<asp:RegularExpressionValidator ID="regexpNumber" runat="server"
ErrorMessage="Numbers only!"
ControlToValidate="txtName"
ValidationExpression="^[0-9]$" />
回答by Liviu M.
The fastest way for validation is using regular expressions. They are harder to understand but offer better performance.
最快的验证方法是使用正则表达式。它们更难理解,但提供更好的性能。
But you could do it also using string functions. Which is easier if you don't know regex but is less performant. This could be a viable option, depending on how hard the validation is.
但是你也可以使用字符串函数来做到这一点。如果您不知道正则表达式但性能较差,这会更容易。这可能是一个可行的选择,具体取决于验证的难度。
Hereand hereare some posts that will help you with code samples.
回答by David T. Macknet
Agreed that Regular Expressions might be faster, but ... well, here's how I've done it. Basically, this code is for a UserControl which contains a label, a text box, and an error provider. It also has various other properties, but here's the bit which deals with validation.
同意正则表达式可能会更快,但是......好吧,这就是我所做的。基本上,此代码用于包含标签、文本框和错误提供程序的 UserControl。它还有各种其他属性,但这里是处理验证的部分。
I do use this on the TextChanged event, because I don't want the user to continue typing if it's an invalid character; the rule checking "eats" the invalid character.
我确实在 TextChanged 事件上使用它,因为如果它是无效字符,我不希望用户继续输入;规则检查“吃掉”了无效字符。
Public Enum CheckType
ctString = 0
ctReal = 1
ctDecimal = 2
ctInteger = 3
ctByte = 4
End Enum
Private mAllowNegative As Boolean = True
Private mAllowNull As Boolean = True
Private mCheckType As CheckType = CheckType.ctString
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
RuleCheckMe()
End Sub
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub RuleCheckMe()
'// Rule Checking
If Me.TextBox1.TextLength = 0 Then
If mAllowNull = False Then
Me.epMain.SetError(Me.TextBox1, "You are required to provide this value.")
Me.Valid = False
Else
Me.epMain.Clear()
Me.Valid = True
End If
Else
Select Case mCheckType
Case CheckType.ctString
If mInputMask.Length > 0 Then
'TODO: Figure out how to cope with input masks!
Me.Valid = True
Else
Me.Valid = True
End If
Case Else '// right now we're only testing for numbers...
If Not IsNumeric(Me.TextBox1.Text) And Me.TextBox1.Text <> "." And Me.TextBox1.Text <> "-" Then
If Not String.IsNullOrEmpty(Me.TextBox1.Text) Then
Me.TextBox1.Text = Me.TextBox1.Text.Remove(Me.TextBox1.Text.Length - 1, 1)
Me.TextBox1.SelectionStart = Me.TextBox1.Text.Length
End If
Me.epMain.SetError(Me.TextBox1, "This field does not accept non-numeric values.")
Me.Valid = False
ElseIf mAllowNegative = False And Me.TextBox1.Text.StartsWith("-") Then
Me.TextBox1.Text = Me.TextBox1.Text.Remove(Me.TextBox1.Text.Length - 1, 1)
Me.epMain.SetError(Me.TextBox1, "This field does not accept negative values.")
Me.Valid = False
ElseIf mCheckType = CheckType.ctByte And CType(Me.TextBox1.Text, Integer) > 255 Then
Me.epMain.SetError(Me.TextBox1, "This field does not accept values greater than 255.")
Me.Valid = False
Else
Me.epMain.Clear()
Me.Valid = True
End If
End Select
End If
End Sub
<System.ComponentModel.Browsable(True), _
System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Visible), _
System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always), _
System.ComponentModel.Category("Data")> _
Public Property AllowNegative() As Boolean
<System.Diagnostics.DebuggerStepThrough()> _
Get
Return mAllowNegative
End Get
<System.Diagnostics.DebuggerStepThrough()> _
Set(ByVal value As Boolean)
mAllowNegative = value
End Set
End Property
<System.ComponentModel.Browsable(True), _
System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Visible), _
System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always), _
System.ComponentModel.Category("Data")> _
Public Property AllowNull() As Boolean
<System.Diagnostics.DebuggerStepThrough()> _
Get
Return mAllowNull
End Get
<System.Diagnostics.DebuggerStepThrough()> _
Set(ByVal value As Boolean)
mAllowNull = value
End Set
End Property
<System.ComponentModel.Browsable(True), _
System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Visible), _
System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always), _
System.ComponentModel.Category("Data")> _
Public Property DataTypeCheck() As CheckType
<System.Diagnostics.DebuggerStepThrough()> _
Get
Return mCheckType
End Get
<System.Diagnostics.DebuggerStepThrough()> _
Set(ByVal value As CheckType)
mCheckType = value
End Set
End Property
回答by Rabin Khadka
just go to the keyup event of text box and enter the following code
只需转到文本框的keyup事件并输入以下代码
100% it will work
100%它会起作用
if(Not Char.IsNumber(Chrw(e.Keycode))) Then
Messagebox.show ("only numeric values ")
textbox1.text=""
end if
回答by mark diaz
i would like to share my text box validator..
我想分享我的文本框验证器..
Dim errProvider As New ErrorProvider
' Verify that this field is not blank.
Private Sub txtValidating(sender As Object,
e As System.ComponentModel.CancelEventArgs) Handles _
txtName.Validating, txtStreet.Validating, txtCity.Validating,
txtState.Validating, txtZip.Validating
' Convert sender into a TextBox.
Dim txt As TextBox = DirectCast(sender, TextBox)
' See if it's blank.
If (txt.Text.Length > 0) Then
' It's not blank. Clear any error.
errProvider.SetError(txt, “”)
Else
' It's blank. Show an error.
errProvider.SetError(txt, “This field is required.”)
End If
End Sub
' See if any field is blank.
Private Sub Form1_FormClosing(sender As Object,
e As FormClosingEventArgs) Handles Me.FormClosing
If (txtName.Text.Length = 0) Then e.Cancel = True
If (txtStreet.Text.Length = 0) Then e.Cancel = True
If (txtCity.Text.Length = 0) Then e.Cancel = True
If (txtState.Text.Length = 0) Then e.Cancel = True
If (txtZip.Text.Length = 0) Then e.Cancel = True
End Sub
回答by Isa Ashan
Private Sub TxtEmployeenumber_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtEmployeenumber.KeyPress
Dim c As Char
c = e.KeyChar
If Not (Char.IsDigit(c) Or c = "." Or Char.IsControl(c)) Then
e.Handled = True
MsgBox("numeric texts only")
End If
End Sub