1

I have multiple textboxes on my windows form, and 1 button that checks if the information inside the textbox is valid. To validate each textbox I'm using Regular Expression.

Example of my textboxes:

  1. First_Name_textbox
  2. Phone_Number_textbox
  3. Date_Of_Birth_textbox
  4. Credit_Card_textbox etc...

Goal: Instead of writing a bunch of if-else validation statements for each textbox like this example below. How can I check all the textboxes and display a message in a more neater way? Neater meaning less code. I find that many if-else statements can make the code messy.

Example of error messages:

  1. First Name was not correct
  2. Phone Number was not correct
  3. Birthday is not in correct format

etc...

if(FirstName_Regex.IsMatch(First_Name_textbox.Text))
{
}
else
{
  MessageBox.Show("Invalid first name");
} 


if(PhoneNumber_Regex.IsMatch(Phone_Number_textbox.Text))
{
}
else
{
  MessageBox.Show("Invalid Phone Number");
} 


if(Credit_Regex.IsMatch(Credit_Card_textbox.Text))
{
}
else
{
  MessageBox.Show("Invalid Credit Card informationr");
} 
taji01
  • 2,527
  • 8
  • 36
  • 80
  • possible duplicate of [validation of multiple textboxes](http://stackoverflow.com/questions/5087844/validation-of-multiple-textboxes) – Marko Juvančič Aug 18 '15 at 08:00
  • Please elaborate on what you mean by *display a message in a more neater way*. Right now what you want to achieve is not clear. – Frédéric Hamidi Aug 18 '15 at 08:01
  • possible duplicate of [Foreach Control in form, how can I do something to all the TextBoxes in my Form?](http://stackoverflow.com/questions/1499049/foreach-control-in-form-how-can-i-do-something-to-all-the-textboxes-in-my-form) In short, iterate through all `Control` elements and check if the current control is a `TextBox`. Code: see link. – jAC Aug 18 '15 at 08:02
  • One approach is to validate as user is typing. Then you would have flag somewhere (either in control or in bool array), which then you can check for all textboxes with a single linq statement. For detailed error message however you can't avoid `if` or using dictionary. Keep current approach If validation is complex. While multiple `if` looks cumbersome it's the simplest and easiest to maintain approach. – Sinatr Aug 18 '15 at 08:02
  • Have a read of http://stackoverflow.com/questions/8915151/c-sharp-validating-input-for-textbox-on-winforms – Paul Zahra Aug 18 '15 at 08:02
  • Display a message meaning if first name was written like this: John12. A messagebox will appear letting the user know MessageBox.Show("Invalid first name"); @FrédéricHamidi – taji01 Aug 18 '15 at 08:05

0 Answers0