DCSIMG
Extending string type with validation functions using extension methods - Pini Dayan

Pini Dayan

The best thing about a boolean is even if you are wrong, you are only off by a bit.

Extending string type with validation functions using extension methods

Hi, usually programmers tend to ignore the power of regular expressions when they write their programs. Well, to be honest I tend to ignore this power as well. So instead of learning once and for all the syntax for these expression we usually copy them from the Internet and use them whenever we need to.

So i decided to start writing a infrastructure that contains several functions to validate a given string with some regular expression pattern, but instead of just writing a class with some static functions, i wrote the class and functions to be an extension methods to the String type. (Extension methods  are a new feature in C# 3 and You can read about them here http://msdn.microsoft.com/en-us/library/bb383977.aspx)

So here is my solution, and will also attach the files to be downloaded if you with to extend them even more.

The first class is a simple one, it contains only the constants variable for holding the expressions for some of the things i would like to validate:

public class RegularExpressionConstants
{
  //Regular expression for checking if a given string is alpha bet. (e.g aaa , aa9, 931a, not 123).
  public const string IS_ALPHABET = "[a-zA-Z]";

  //Regular expression for checking if a given string is alpha numeric. (e.g aaa , aa9, 931a, and 123).
  public const string IS_ALPHA_NUMERIC = "[a-zA-Z0-9]";

 //Regular expression for checking if a given string is a valid email.
 public const string IS_EMAIL = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";

 //Regular expression for checking if a given string is a valid url.
 public const string IS_URL = @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?"; 
      
 //Regular expression for checking if a given string is a valid url.
 public const string IS_CELLULAR_NUMBER =
         @"^[0][5][0]-\d{7}|[0][5][2]-\d{7}|[0][5][4]-\d{7}|[0][5][7]-\d{7}$";
}

The second class is the String extender which actually extent the string type and make use of the System.Text.RegularExpressions namespace:

public static class RegularExpressionsCheckerExtender
{
   public static bool IsAlphaBet(this string sStringToCheck)
   {
     Regex oIsAlphaBet = new Regex(RegularExpressionConstants.IS_ALPHABET);
     return oIsAlphaBet.IsMatch(sStringToCheck);
   }

  public static bool IsAlphaNumeric(this string sStringToCheck)
  {
    Regex oIsAlphaBet = new Regex(RegularExpressionConstants.IS_ALPHA_NUMERIC);
    return oIsAlphaBet.IsMatch(sStringToCheck);
  }

  public static bool IsEmail(this string sStringToCheck)
  {
     Regex oIsAlphaBet = new Regex(RegularExpressionConstants.IS_EMAIL);
     return oIsAlphaBet.IsMatch(sStringToCheck);
  }

  public static bool IsURL(this string sStringToCheck)
  {
    Regex oIsAlphaBet = new Regex(RegularExpressionConstants.IS_URL);
    return oIsAlphaBet.IsMatch(sStringToCheck);
  }

  public static bool IsIsraeliCellNumber(this string sStringToCheck)
  {
   Regex oIsAlphaBet = new Regex(RegularExpressionConstants.IS_CELLULAR_NUMBER);
   return oIsAlphaBet.IsMatch(sStringToCheck);
  }

  private static bool CheckIfMatch(string sStringToCheck, string sRegExExpression)
  {
     Regex oRegEx = new Regex(sRegExExpression);
     return oRegEx.IsMatch(sStringToCheck);
  }
 }

Here is a simple console application code that test the string extended functions:

class Program
   {
       static void Main(string[] args)
       {
           //Once we added the "using RegularExpressionsStringExtender;" 
           //the string type is being extended
           string sEmail = "pinid@somedomain.com";
           Console.WriteLine(sEmail.IsEmail());

           string sCellPhone = "11111111";
           Console.WriteLine(sCellPhone.IsIsraeliCellNumber());

           string sURL = "http://www.ynet.co.il";
           Console.WriteLine(sURL.IsURL ());

           //...
       }
   }
Here is a link to download the entire solution
 http://blogs.microsoft.co.il/files/folders/pini_dayan/entry210172.aspx

Enjoy

Posted: Jan 12 2009, 10:13 AM by Pini Dayan | with 5 comment(s) |
תגים:,

Comments

Avi Pinto said:

הפרמוט של הפוסט יצא לא טוב, רואים את הגדרות ה CSS בסופו

ובלי קשר - תודה על הפוסט :)

# January 12, 2009 7:08 PM

Pini Dayan said:

היי תודה אבי

סידרתי עד כמה שיכולתי, מקווה שעכשיו זה בסדר

# January 13, 2009 9:58 AM

אמיר said:

היי פיני, אמנם קראתי על ה feature החדש הזה אבל עוד לא ראיתי צורך להשתמש בו, כנראה שלא הבנתי אותו טוב

עכשיו בדוגמא שלך זה ברור ומדהים. מאוד חזק. אפשר ככה להרחיב כל אובייקט ב .net

תודה :-)

# January 13, 2009 10:00 AM

גיא said:

היי,

הפוסט מצויין אבל יש לי בעיה עם הרעיון של Extension Methods במקרה של Validation.

אני חושב שאנחנו לא צריכים להגזים ולקחת את כל הלוגיקה שלנו ולהעביר אותה כמתודה של אובייקטים אלא להשתמש בזה רק במקרים כמו לדוגמה רוצים להחזיר את כל התויים מצד ימין של המחזורת ובמקום לעשות Substring עם חישובים כאלו ואחרים כותבים extension שייקרא Left שמקבל מספר תווים ומחזיר מחרוזת חתוכה מצד שמאל וכדומה.

גיא

# January 13, 2009 11:21 PM

Pini Dayan said:

היי גיא, תודה על התגובה

אני מניח שאתה צודק חלקית. ניתן להתווכח על זה.

בכל מקרה הדוגמא של ולידציות ניתנה רק לצורך הדגמה, זה הרעיון שחשבתי עליו באותו הרגע.

# January 18, 2009 2:40 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: