Home > Articles

  • Print
  • + Share This
This chapter is from the book

3.11. Validating User Input with Regular Expressions

You want to ensure valid user input by using regular expressions to test for validity.

Technique

Create a RegEx object, which exists within the System.Text.RegularExpressions namespace, passing the regular expression in as a parameter to the constructor. Next, call the member method Match using the string you want to validate as a parameter to the method. The method returns a Match object regardless of the outcome. To test whether a match is made, evaluate the Boolean Success property on that Match object as demonstrated in Listing 3.9. It should also be noted that in many cases, the forward slash (\) character is used when working with regular expressions. To avoid compilation errors from inadvertently specifying an invalid control character, use the @ symbol to turn off escape processing.

Listing 3.9 Validating User Input of a Phone Number Using a Regular Expression

using System;
using System.Text.RegularExpressions;

namespace _11_RegularExpressions
{
  class Class1
  {
    [STAThread]
    static void Main(string[] args)
    {
      Regex phoneExp = new Regex( @"^\(\d{3}\)\s\d{3}-\d{4}$" );
      string input;

      Console.Write( "Enter a phone number: " );
      input = Console.ReadLine();
      
      while( phoneExp.Match( input ).Success == false )
      {
        Console.WriteLine( "Invalid input. Try again." );
        Console.Write( "Enter a phone number: " );
        input = Console.ReadLine();
      }

      Console.WriteLine( "Validated!" );
    }
  }
}

Comments

Earlier in this chapter I mentioned that you could perform data validation using the static methods within the System.Char class. You can inspect each character within the input string to ensure it matches exactly what you are looking for. However, this method of input validation can be extremely cumbersome if you have different input types to validate because it requires custom code for each validation. In other words, using the methods in the System.Char class is not recommended for anything but the simplest of data-validation procedures.

Regular expressions, on the other hand, allow you to perform the most advanced input validation possible, all within a single expression. You are in effect passing the parsing of the input string to the regular-expression engine and offloading all the work that you would normally do.

In Listing 3.9, you can see how you create and use a regular expression to test the validity of a phone number entered by a user. The regular expression is similar to the previous expressions used earlier for phone numbers except for the addition of positional markers. The regular expression is valid if a user enters a phone number and nothing else. A match is successful when the Success property within the Match object, which is returned from the Regex.Match method, is true. The only caveat to using regular expressions for input validation is that even though you know the validation failed, you are unable to query the Regex or Match class to see what part of the string failed.

  • + Share This
  • 🔖 Save To Your Account