简体   繁体   English

文本框只能接受10个数字。 在VB.NET中也一样

[英]Textbox has to only accept 10 numbers. No more no less in VB.NET

How do you make a textbox only accept 10 numbers and it could also accept () - 如何使文本框仅接受10个数字,并且还可以接受()-

example: 123-123-1234 or example: 1231231234 or example: (123)123-1234 例如:123-123-1234或例如:1231231234或例如:(123)123-1234

if the text box does not contain any of these example it should give a error message. 如果文本框不包含任何这些示例,则应给出错误消息。

The MaskedTextBox in Windows Forms is designed to restrict input to conform to a pattern and gracefully let the user know if they're entering data that's against that pattern. Windows窗体中的MaskedTextBox旨在限制输入以符合模式,并优雅地让用户知道他们是否正在输入违反该模式的数据。

https://msdn.microsoft.com/en-us/library/vstudio/kkx4h3az(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/vstudio/kkx4h3az(v=vs.110).aspx

You have to do this with server-code, but it is nice to have a client-side validator as well. 您必须使用服务器代码来执行此操作,但是最好也有一个客户端验证器。

Server-side: As Rikkigibson already pointed out, MaskedTextBox is a good control to achieve this. 服务器端:正如Rikkigibson所指出的, MaskedTextBox是实现此目的的一个很好的控件。 Example: 例:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Me.ToolTip1.IsBalloon = True
    Me.MaskedTextBox1.Mask = "00/00/0000"
End Sub

Private Sub MaskedTextBox1_MaskInputRejected(sender as Object, e as MaskInputRejectedEventArgs) Handles MaskedTextBox1.MaskInputRejected
    ToolTip1.ToolTipTitle = "Invalid Input"
    ToolTip1.Show("We're sorry, but only digits (0-9) are allowed in dates.", MaskedTextBox1, 5000)
End Sub

Read here about the Mask property . 在这里阅读有关Mask property

Client-side: It is good to have a client-side validation as well, so, no request with wrong value in the textbox would reach and burden your server. 客户端:最好也进行客户端验证,因此,文本框中错误值的请求都不会到达服务器并给服务器增加负担。 To do this in jQuery, you can handle the .keyup() event of your textbox. 为此,您可以在jQuery中处理.keyup()事件。 So, if you have a validation function, and we assume that selector corresponds to your textbox, then you should write a code, like 因此,如果您具有验证功能,并且我们假设选择器与您的文本框相对应,那么您应该编写代码,例如

$(selector).keyup(function(e) {
    if (validation(e)) {
        //it is valid
    } else {
        //it is not valid
    }
});

EDIT: 编辑:

I have seen you have a problem with the number of digits as well. 我已经看到您也有数字位数的问题。 This is how you get the number of digits in a String using vb and this is how you get it in Javascript. 是使用vb获取String中数字位数的方式, 也是使用Javascript获取数字位数的方式。

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

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