简体   繁体   中英

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 () -

example: 123-123-1234 or example: 1231231234 or example: (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.

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. 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 .

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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