How to Validate c# textbox visual studio 13

325 Views Asked by At

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(); 
    } 
}
2

There are 2 best solutions below

2
Jeremy Kato On

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.

0
Bharat Gupta On

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