Use string extension methods to validate Social Security numbers in C#

[Social Security numbers]

This example defines three extension methods that return true if strings contain Social Security numbers.

Recall that you must add extension methods to a static class and that the methods must be static. This example begins by defining a Matches string extension method to determine whether a string matches a regular expression.

using System.Text.RegularExpressions;
public static bool Matches(this string value, string expression)
    return Regex.IsMatch(value, expression);

This code simply invokes the Regex class’s static IsMatch method passing it a string and a regular expression. That method returns true or false to indicate whether the string matches the expression. The extension method simply returns that result.

Once you’ve defined the Matches method, it’s easy to make other extension methods that validate particular formats. The following code shows how this example validates Social Security numbers with or without dashes, or with either format.

public static bool IsValidSsnWithDashes(this string value)
    return value.Matches(@"^\d{3}-\d{2}-\d{4}$");

public static bool IsValidSsnWithoutDashes(this string value)
    return Regex.IsMatch(value, @"^\d{9}$");

public static bool IsValidSsn(this string value)
    return value.Matches(@"^(?:\d{9}|\d{3}-\d{2}-\d{4})$");

These methods differ only in the regular expressions they use. The first method, IsValidSsnWithDashes, uses the pattern @”^\d{3}-\d{2}-\d{4}$” to match Social Security numbers of the form ddd-dd-dddd where d is any digit. Notice how the code uses the @ symbol to make a verbatim string literal so the backslashes are not treated as special characters in the string.

The initial ^ matches the beginning of the string. The \d token means “any digit.” The {3} means repeat the previous \d token 3 times, so the first part of the expression matches 3 digits at the beginning of a string. The dash - is treated as a literal character so the string must contain a dash. The expression then uses \d and count specifiers again to match 2 digits, a dash, and 4 digits. The final $ matches the end of the string.

The second method, IsValidSsnWithoutDashes, uses the pattern @”^\d{9}$” to match Social Security numbers of the form ddddddddd. This regular expression simply matches 9 digits.

The third method, IsValidSsn, matches Social Security numbers with or without dashes. Its regular expression includes the two previous regular expressions separated by a vertical bar |, which indicates that either one of the patterns can form a match.

With these extension methods, it is easy for the main program to validate Social Security numbers. The main form uses TextChanged event handlers to give each TextBox a yellow background if it does not contain data in the appropriate format. The following code shows how the TextBox that allows either format works.

private void txtEither_TextChanged(object sender, EventArgs e)
    if (txtEither.Text.IsValidSsn())
        txtEither.BackColor = SystemColors.Window;
        txtEither.BackColor = Color.Yellow;

This code simply calls the IsValidSsn extension method to see if the text has an appropriate format and then sets the control’s BackColor property accordingly.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in extension methods, extensions, regular expressions, strings and tagged , , , , , , , , , . Bookmark the permalink.

2 Responses to Use string extension methods to validate Social Security numbers in C#

  1. Adrian says:

    The regular expression @”^\d{9}|\d{3}-\d{2}-\d{4}$” is equivalent to @”(?:^\d{9})|(?:\d{3}-\d{2}-\d{4}$)”, so the anchors do not work as desired. The effect of this can be seen by entering “123456789xx” or “yy123-45-6789” into the “Either” box in the demo program.

    Need to make the “|” not apply to the anchors. Changing the regular expression to @”^(?:\d{9}|\d{3}-\d{2}-\d{4})$” works.

    Otherwise, great article.

Leave a Reply

Your email address will not be published. Required fields are marked *