BLOG.CSHARPHELPER.COM: Use string extension methods to validate Social Security numbers in C#
Use string extension methods to validate Social Security numbers in C#
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 the string and the regular expression. That method returns true or false to indicate whether the string matches the expression. This 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.
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 \d token meaks "any digit." The {3} means repeat the previous \d token 3 times, so the first part of the expression matches 3 digits. 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 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 on either side of the | 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.
This code simply calls the IsValidSsn extension method to see if the text has an appropriate format and then sets the TextBox's BackColor property accordingly.
Comments