Click here to Skip to main content
14,691,039 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
using System.Text.RegularExpressions;

Regex re = new Regex("^9[0-9]{9}");
if (re.IsMatch(txtMob.Text.Trim()) == false || txtMob.Text.Length > 10)
  MessageBox.Show("Invalid  Mobile Number !!");

I have implemented the above code and it displays invalid mobile number for any given number.

I would like to implement validations, which would show a "Characters are not allowed" message when any characters are typed and show an invalid number message when more than 10 digits are entered.

Please help me out!
Updated 11-Jun-18 1:17am

on TextBox KeyPress event write this code :

private void txy_Keypress(object sender, KeyPressEventArgs e)
            if (!char.IsNumber(e.KeyChar) & (Keys)e.KeyChar != Keys.Back & (Keys)e.KeyChar != Keys.Enter)

                e.Handled = true;


and on TextChanged event write this code :

if (txtMob.Text.Length > 10)

MessageBox.Show("Invalid Mobile Number !!");


or set text Maxlenth proparty set 10

hope this help
rbnsubedi 29-Jun-11 13:06pm
Thank u so much!!! its works!!!cheeses:)
Sergey Alexandrovich Kryukov 30-Jun-11 19:16pm
This is not bad. I voted 5, disagree with the vote of 1. It's good that Keys.Back is taken into account. Validation can be done on top of this.
I wouldn't do it by using keypresses in a TextBox. How I do my validations is to accept a free-typed phone number, then go a strip all non-numeric characters from the input, validate the number for the country in question, the reformat the number as a string according to the rules for that country.

That allows used to type numbers in in anyn format they chose and I still get the data I want without frustrating the customer.

By the way, youre regex pattern demands that every number typed in be 10 digits long and always start with a 9.
Sergey Alexandrovich Kryukov 30-Jun-11 19:19pm
I must say I disagree if you voted 1 for the answer by Rajesh. Validation could be used on top of filtering by KeyPressed. If the filtering is simple, it should always be used. If it is complex (for example, position-dependent as some try to design), it could confuse the used and should never be used.
Dave Kreskowiak 30-Jun-11 21:30pm
Filtering is almost never simple. There's always going to be that next "requirement" that screws up what you've already done.
Maybe, but I mean this particular case and some similar ones: filter out all but digits and backspace (may be one or two more). This is used all the time and not confusing at all.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900