-3

How should I validate textbox for only accepting numbers, only alphabets other important validations that could be needed. Using properties window of visual studio. Or any other best way.

private void txt5ValGood_TextChanged(object sender, EventArgs e) 
{ 
    if (System.Text.RegularExpressions.Regex.IsMatch(txt5ValGood.Text, "[^0-9]+")) 
    { 
        txt5ValGood.Text = System.Text.RegularExpressions.Regex.Match(txt5ValGood.Text, "[0-9]+").ToString(); 
    } 
}
MethodMan
  • 18,625
  • 6
  • 34
  • 52
  • you do this by first writing some code.. can you show us what you have tried thus far on your own.. also show us what other special characters are acceptable beside eliminating alpha chars i.e `A-Z, a-z` – MethodMan Jun 01 '16 at 14:23
  • http://stackoverflow.com/questions/8915151/c-sharp-validating-input-for-textbox-on-winforms – Yusril Maulidan Raji Jun 01 '16 at 14:28
  • Okay, i will post it – Lakhan Sindhi Jun 01 '16 at 14:35
  • Google is your friend – jayvee Jun 01 '16 at 16:01
  • here is a code that i have worked on for accepting only numbers `private void txt5ValGood_TextChanged(object sender, EventArgs e) { if (System.Text.RegularExpressions.Regex.IsMatch(txt5ValGood.Text, "[^0-9]+")) { txt5ValGood.Text = System.Text.RegularExpressions.Regex.Match(txt5ValGood.Text, "[0-9]+").ToString(); } }` – Lakhan Sindhi Jun 05 '16 at 13:23
  • @MethodMan please check the above code i want this type of validation by using windows controls. – Lakhan Sindhi Jun 05 '16 at 13:34
  • FYI do not post code in your comments you need to for future reference, edit your original question and post the code there ...! – MethodMan Jun 06 '16 at 13:40

2 Answers2

0

This is a duplicate, but I'll take a quick second to answer it.

What I've done in the past is let the user enter text in a text box, and wait for an event to require validating it - usually them pressing a button or some event that indicates they want to do something with what they just entered.

In the code for that event, what you can do is iterate through the string, and check each character for whatever requirement you desire. For instance, for a digit check you could do:

for (int i = 0; i < yourString.length; i++) {
 if (!Char.IsDigit(yourString, i)) {
  DisplayError();
  return;
 }
}

It would be helpful to take a look at the MSDN page for char methods to see how these checks are used.

Jeremy Kato
  • 467
  • 5
  • 12
0

You must give a look at MaskedTextBox control. It requires you to set a mask for the required valid input on a textbox.

Eg: A mask of 00000 will allow the textbox to only accept numbers of five digits. You can play around with it and achieve brilliant results.

MaskedTextBox at MSDN and an example

Bharat Gupta
  • 2,628
  • 1
  • 19
  • 27