Validating User Input With Regular Expressions

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

// ensures no TextBoxes are empty  
if (lastNameTextBox.Text == "" || firstNameTextBox.Text == "" || addressTextBox.Text == "" || cityTextBox.Text == "" || stateTextBox.Text == "" || zipCodeTextBox.Text == "" || phoneTextBox.Text == "")  
{  
       // display popup box  
       MessageBox.Show("Please fill in all fields","Error",MessageBoxButton.OK,MessageBoxImage.Error);  
       firstNameTextBox.Focus(); // set focus to lastNameTextBox  
       return;  
 } // 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.

if (!Regex.Match(firstNameTextBox.Text, "^[A-Z][a-zA-Z]*$").Success)  
{  
     // first name was incorrect  
     MessageBox.Show("Invalid first name", "Message", MessageBoxButton.OK,MessageBoxImage.Error);  
     firstNameTextBox.Focus();  
     return;  
} 

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

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Windows;  
using System.Windows.Controls;  
using System.Windows.Data;  
using System.Windows.Documents;  
using System.Windows.Input;  
using System.Windows.Media;  
using System.Windows.Media.Imaging;  
using System.Windows.Navigation;  
using System.Windows.Shapes;  
using System.Text.RegularExpressions;   
namespace MyRND_in_WPF  
{  
    /// <summary>  
    /// Interaction logic for MainWindow.xaml  
    /// </summary>  
    public partial class MainWindow : Window  
    {  
        public MainWindow()  
        {  
            InitializeComponent();  
        }   
        private void btnOK_Click(object sender, RoutedEventArgs e)  
        {  
            // ensures no TextBoxes are empty  
            if (lastNameTextBox.Text == "" || firstNameTextBox.Text == "" || addressTextBox.Text == "" || cityTextBox.Text == "" || stateTextBox.Text == "" || zipCodeTextBox.Text == "" ||  
phoneTextBox.Text == "")  
            {  
                // display popup box  
                MessageBox.Show("Please fill in all fields","Error",MessageBoxButton.OK,MessageBoxImage.Error);  
                firstNameTextBox.Focus(); // set focus to lastNameTextBox  
                return;  
            } // end if   
            // if first name format invalid show message  
            if (!Regex.Match(firstNameTextBox.Text, "^[A-Z][a-zA-Z]*$").Success)  
            {  
                // first name was incorrect  
                MessageBox.Show("Invalid first name", "Message", MessageBoxButton.OK,MessageBoxImage.Error);  
                firstNameTextBox.Focus();  
                return;  
            } // end if   
            // if last name format invalid show message  
            if (!Regex.Match(lastNameTextBox.Text, "^[A-Z][a-zA-Z]*$").Success)  
            {  
                // last name was incorrect  
                MessageBox.Show("Invalid last name", "Message", MessageBoxButton.OK,MessageBoxImage.Error);  
                lastNameTextBox.Focus();  
                return;  
            }// end if            
            // if address format invalid show message  
            if (!Regex.Match(addressTextBox.Text, @"^[0-9]+\s+([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$").Success)  
            {  
                // address was incorrect  
                MessageBox.Show("Invalid address", "Message", MessageBoxButton.OK,MessageBoxImage.Error);  
                addressTextBox.Focus();  
                return;  
            } // end if   
            // if city format invalid show message  
            if (!Regex.Match(cityTextBox.Text, @"^([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$").Success)  
            {  
                // city was incorrect  
                MessageBox.Show("Invalid city", "Message", MessageBoxButton.OK,MessageBoxImage.Error);  
                cityTextBox.Focus();  
                return;  
            }// end if   
            // if state format invalid show message  
            if (!Regex.Match(stateTextBox.Text, @"^([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$").Success)  
            {  
                // state was incorrect  
                MessageBox.Show("Invalid state", "Message", MessageBoxButton.OK,MessageBoxImage.Error);  
                stateTextBox.Focus();  
                return;  
            } // end if   
            // if zip code format invalid show message  
            if (!Regex.Match(zipCodeTextBox.Text, @"^\d{5}$").Success)  
            {  
                // zip was incorrect  
                MessageBox.Show("Invalid zip code", "Message", MessageBoxButton.OK,MessageBoxImage.Error);  
                zipCodeTextBox.Focus();  
                return;  
            } // end if  
            // if phone number format invalid show message  
            if (!Regex.Match(phoneTextBox.Text, @"^[1-9]\d{2}-[1-9]\d{2}-\d{4}$").Success)  
            {  
                // phone number was incorrect  
                MessageBox.Show("Invalid phone number", "Message", MessageBoxButton.OK,MessageBoxImage.Error);  
                phoneTextBox.Focus();  
                return;  
            }// end if   
            // information is valid, signal user and exit application  
            this.Hide(); // hide main window while MessageBox displays  
            MessageBox.Show("Thank You!", "Information Correct",MessageBoxButton.OK,MessageBoxImage.Information);   
        }  
    }  
}  

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.


Similar Articles