Validating User Input With Regular Expressions

This article explains how to use Regular Expressions (the Regex class of the System.Text.RegularExpressions namespace) in C# and .NET.

Introduction


This article explains how to use Regex in a Windows application. The code example uses Regular Expressions in C# to validate name, address, and telephone number input by a user. Before we look at the code sample, I would like to provide a little explanation of Regular Expressions.

Regular Expression


Regular Expressions are specially formatted strings for specifying patterns in text. They can be useful during information validation, to ensure that data is in a specified format. For example, a ZIP code must consist of five digits, and the last name must start with a capital letter. Compilers use Regular Expressions to validate the syntax of programs. If the program code does not match the Regular Expression then the compiler indicates that there is a syntax error.

Let's go for the details of my illustration. When a user clicks the OK button, the program checks to ensure that none of the fields are empty. If one or more fields are empty then the program displays a message to the user that all fields must be filled in before the program can validate the input information.

Validating User Input With Regular Expressions

 

  1. // ensures no TextBoxes are empty  
  2. if (lastNameTextBox.Text == "" || firstNameTextBox.Text == "" || addressTextBox.Text == "" || cityTextBox.Text == "" || stateTextBox.Text == "" || zipCodeTextBox.Text == "" || phoneTextBox.Text == "")  
  3. {  
  4.        // display popup box  
  5.        MessageBox.Show("Please fill in all fields","Error",MessageBoxButton.OK,MessageBoxImage.Error);  
  6.        firstNameTextBox.Focus(); // set focus to lastNameTextBox  
  7.        return;  
  8.  } // end if  

The code above calls the firstNameTextBox's Focus method to place the cursor in the firstNameTextBox. If there are no empty fields, then the following code validates the first name by calling the static method Match of the Regex class, passing both the string to validate and the Regular Expression as arguments. Method Match returns a Match object.

This object contains a Success property that indicates whether a method Match's first argument matches the pattern specified by the Regular Expression in the second argument. If the value of Success is false (i.e., there was no match), then it displays an error message and sets the focus back to the firstNameTextBox so that the user can retype the input and terminate the event handler. If there is a match, then the event handler proceeds to validate the first name.
  1. if (!Regex.Match(firstNameTextBox.Text, "^[A-Z][a-zA-Z]*$").Success)  
  2. {  
  3.      // first name was incorrect  
  4.      MessageBox.Show("Invalid first name""Message", MessageBoxButton.OK,MessageBoxImage.Error);  
  5.      firstNameTextBox.Focus();  
  6.      return;  
  7. }  

 

Validating User Input With Regular Expressions

 

This process continues until the event handler validates the user input in all the TextBoxes or until a validation fails. If all of the fields contain valid information, the program displays a message dialog stating this and the program exits when the user dismisses the dialog.

Code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Windows;  
  6. using System.Windows.Controls;  
  7. using System.Windows.Data;  
  8. using System.Windows.Documents;  
  9. using System.Windows.Input;  
  10. using System.Windows.Media;  
  11. using System.Windows.Media.Imaging;  
  12. using System.Windows.Navigation;  
  13. using System.Windows.Shapes;  
  14. using System.Text.RegularExpressions;   
  15. namespace MyRND_in_WPF  
  16. {  
  17.     /// <summary>  
  18.     /// Interaction logic for MainWindow.xaml  
  19.     /// </summary>  
  20.     public partial class MainWindow : Window  
  21.     {  
  22.         public MainWindow()  
  23.         {  
  24.             InitializeComponent();  
  25.         }   
  26.         private void btnOK_Click(object sender, RoutedEventArgs e)  
  27.         {  
  28.             // ensures no TextBoxes are empty  
  29.             if (lastNameTextBox.Text == "" || firstNameTextBox.Text == "" || addressTextBox.Text == "" || cityTextBox.Text == "" || stateTextBox.Text == "" || zipCodeTextBox.Text == "" ||  
  30. phoneTextBox.Text == "")  
  31.             {  
  32.                 // display popup box  
  33.                 MessageBox.Show("Please fill in all fields","Error",MessageBoxButton.OK,MessageBoxImage.Error);  
  34.                 firstNameTextBox.Focus(); // set focus to lastNameTextBox  
  35.                 return;  
  36.             } // end if   
  37.             // if first name format invalid show message  
  38.             if (!Regex.Match(firstNameTextBox.Text, "^[A-Z][a-zA-Z]*$").Success)  
  39.             {  
  40.                 // first name was incorrect  
  41.                 MessageBox.Show("Invalid first name""Message", MessageBoxButton.OK,MessageBoxImage.Error);  
  42.                 firstNameTextBox.Focus();  
  43.                 return;  
  44.             } // end if   
  45.             // if last name format invalid show message  
  46.             if (!Regex.Match(lastNameTextBox.Text, "^[A-Z][a-zA-Z]*$").Success)  
  47.             {  
  48.                 // last name was incorrect  
  49.                 MessageBox.Show("Invalid last name""Message", MessageBoxButton.OK,MessageBoxImage.Error);  
  50.                 lastNameTextBox.Focus();  
  51.                 return;  
  52.             }// end if            
  53.             // if address format invalid show message  
  54.             if (!Regex.Match(addressTextBox.Text, @"^[0-9]+\s+([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$").Success)  
  55.             {  
  56.                 // address was incorrect  
  57.                 MessageBox.Show("Invalid address""Message", MessageBoxButton.OK,MessageBoxImage.Error);  
  58.                 addressTextBox.Focus();  
  59.                 return;  
  60.             } // end if   
  61.             // if city format invalid show message  
  62.             if (!Regex.Match(cityTextBox.Text, @"^([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$").Success)  
  63.             {  
  64.                 // city was incorrect  
  65.                 MessageBox.Show("Invalid city""Message", MessageBoxButton.OK,MessageBoxImage.Error);  
  66.                 cityTextBox.Focus();  
  67.                 return;  
  68.             }// end if   
  69.             // if state format invalid show message  
  70.             if (!Regex.Match(stateTextBox.Text, @"^([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$").Success)  
  71.             {  
  72.                 // state was incorrect  
  73.                 MessageBox.Show("Invalid state""Message", MessageBoxButton.OK,MessageBoxImage.Error);  
  74.                 stateTextBox.Focus();  
  75.                 return;  
  76.             } // end if   
  77.             // if zip code format invalid show message  
  78.             if (!Regex.Match(zipCodeTextBox.Text, @"^\d{5}$").Success)  
  79.             {  
  80.                 // zip was incorrect  
  81.                 MessageBox.Show("Invalid zip code""Message", MessageBoxButton.OK,MessageBoxImage.Error);  
  82.                 zipCodeTextBox.Focus();  
  83.                 return;  
  84.             } // end if  
  85.             // if phone number format invalid show message  
  86.             if (!Regex.Match(phoneTextBox.Text, @"^[1-9]\d{2}-[1-9]\d{2}-\d{4}$").Success)  
  87.             {  
  88.                 // phone number was incorrect  
  89.                 MessageBox.Show("Invalid phone number""Message", MessageBoxButton.OK,MessageBoxImage.Error);  
  90.                 phoneTextBox.Focus();  
  91.                 return;  
  92.             }// end if   
  93.             // information is valid, signal user and exit application  
  94.             this.Hide(); // hide main window while MessageBox displays  
  95.             MessageBox.Show("Thank You!""Information Correct",MessageBoxButton.OK,MessageBoxImage.Information);   
  96.         }  
  97.     }  
  98. }  

 

Summary


In the preceding illustration, we saw how to use Regular Expressions to validate input using the Regex class of the System.Text.RegularExpressions namespace.