Validation Using Regular Expressions

Regular expression is a great way to validate data provided by a user to the  fields of a form. Suppose that a user should input an age rather than a name, or  an address rather than a gender, you can use the power of regular expressions to  validate them. The following example creates a simple windows forms application  that demonstrates the use of regular expression in validating each field of a  form. Create a new windows forms application and name it RegexValidation.

Figure 1

 Label  Type  Name  Property Values
 1  Label  firstNameTextBox
 2  Label  lastNameTextBox
 3  Label  ageTextBox
 4  Label  genderTextBox
 5  Label  addressTextBox
 6  Label  zipCodeTextBox
 7  Button  submitButton  Text  Submit

Although we can use radio buttons for the Gender field, we will be using a  text box to demonstrate validation of text using regular expressions. Double  click the submitButton to generate an event  handler for its Click event. Be sure to import System.Text for the StringBuilder class that we  will use and System.Text.RegularExpressions for  the Regex class.

using System.Text;
using System.Text.RegularExpressions;

We should also declare a StringBuilder and Regex members in our Program class.

private StringBuilder errors;
private Regex validator;

Use the following code for the Click event  handler of submitButton.

private void submitButton_Click(object sender, EventArgs e)
{
    if (AreFieldsValid())
    {
        //Do task here
    }
}

Notice that the event handler calls the AreFieldsValid() which is a method that we will create that will check  each field for validation errors. The method will return a true if no errors have  been detected and false if at least one validation error is detected. If it  returns true, then you can insert the code to do  if all the fields are valid. The following is the code for AreFieldsValid() method.

private bool AreFieldsValid()
{
    errors = new StringBuilder();
 
    //Validate First Name and Last Name
    validator = new Regex(@"^([A-Z][a-z]+)(\s[A-Z][a-z]+)*$");
 
    if (!validator.Match(firstNameTextBox.Text).Success)
        errors.AppendLine("First name is not in the proper format.");
 
    if (!validator.Match(lastNameTextBox.Text).Success)
        errors.AppendLine("Last name is not in the proper format.");
 
    //Validate Age
    validator = new Regex(@"^\d{1,2}$");
 
    if (!validator.IsMatch(ageTextBox.Text))
        errors.AppendLine("Invalid Age.");
 
    //Validate Gender
    validator = new Regex(@"^([M|m]ale|[F|f]emale)$");
 
    if (!validator.IsMatch(genderTextBox.Text))
        errors.AppendLine("Invalid Gender.");
 
    //Validate Address
    validator = new Regex(@"^[0-9]+(\s[a-zA-Z]+)+$");
 
    if (!validator.IsMatch(addressTextBox.Text))
        errors.AppendLine("Address is not in the proper format.");
 
    //Validate ZipCode
    validator = new Regex(@"^\d{4}$");
 
    if (!validator.IsMatch(zipCodeTextBox.Text))
        errors.AppendLine("Invalid zip code");
 
    if (errors.ToString() == String.Empty)
    {
        return true;
    }
    else
    {
        MessageBox.Show(errors.ToString(), "Validation Failed", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
 
        return false;
    }
}

Example 1

Line 3 creates a new instance of the StringBuilder  class. Using its parameterless constructor instantiates it with an empty  string. Line 6 creates the regular expression pattern for the first and last  names. Since first and last names have the same pattern, they can simply share  with the same regular expression. Lines 8 and 11 tests if the first and last  names provided by the user is valid by using the Match()  method of the Regex class and passing the text  inside the text boxes. The Match() method returns a Match  object where you can access the Success property  indicating if whether the given text matches the pattern. If the matching is not  successful, then we used the AppendLine() method  of the StringBuilder class to add a message to the errors that will be presented to the user at the  end of the validation. Lines 15 creates another Regex  object with a new regular expression pattern that will be used for the age. In  line 17, we used the IsMatch() method of the Regex class instead of the Match() method which is much simpler but only has one purpose, to tell  whether a specified string matches the given pattern. If it does, IsMatch() will return true,  otherwise false. For each field to validate, we  simply create a corresponding Regex object with the  proper string pattern. If a field does not match a pattern, then an error  message is appended to the content of errors.  After we have tested every field for validity, line 38 tests if the content of errorsis empty. Empty means that no errors have  been added to its content, therefore, all the fields are valid and true was returned to the caller. If the errors have  contents, then we print in a message box to notify the user of the validation  errors and return false to the caller.

We have seen one technique of validation using regular expressions. There are  more ways to do validation such as using an ErrorProvider  control or the Validating and Validated events.