Date Validation Using the .NET Globalization Classes

Welcome to this week's installment of .NET Tips & Techniques! Each week, award-winning Architect and Lead Programmer Tom Archer from the Archer Consulting Group demonstrates how to perform a practical .NET programming task.

Most times, the easiest means of validating a user-entered date is by providing a masked edit control that forces the user to enter valid numbers into the month/day/year parts of the field. However, a system you maintain many times won't have a masked edit. It instead allows the user to enter the date value in a "free form" edit control, which necessitates a manual validation of the entered date.

One obvious way to address this problem is to check each set of digits (representing the day, month, and year) similar to the following:

static bool ManuallyValidate(String date)
{
   // check month in mmddyy or mmddyyyy format
   if (Convert.ToInt32(date.Substring(0, 2)) <= 12
   && Convert.ToInt32(date.Substring(0, 2)) >= 1)
      ...    // Continue checking other digits
      return true;
   else
      return false;
}

However, one obvious shortcoming of this approach is that it works with only one date format—unless you include a format parameter and a lot of conditional code for each date format type. A much more robust and easy way to deal with this problem is to use the types provided via the .NET Globalization namespace. Here's an example of using the DateTimeFormatInfo and DateTime types to validate your dates in three lines of code:
static bool ValidateDate(String date, String format)
{
   try
   {
      System.Globalization.DateTimeFormatInfo dtfi = new
             System.Globalization.DateTimeFormatInfo();
      dtfi.ShortDatePattern = format;
      DateTime dt = DateTime.ParseExact(date, "d", dtfi);
   }
   catch(Exception)
   {
      return false;
   }
   return true;
}

As you can see, the ValidateDate method takes a String that represents the date to be validated and a String that represents the format to be checked, such as yymm or MMdd. The client then would call this function as follows:

BOOL success;
success = ValidateDate("3403", "MMmm");    // false as 34 is not a valid month
success = ValidateDate("3403", "yymm");    // true
success = ValidateDate("1212", "MMdd");    // true

Obviously, you could extend this example further, but this article should serve as a good introduction to some of what the Globalization namespace can do and how easy it is to use. For a list of the various patterns that you can use, simply look up the topic DateTimeFormatInfo in online help, as well as the ShortDatePattern vs. LongDatePattern topic.



About the Author

Tom Archer - MSFT

I am a Program Manager and Content Strategist for the Microsoft MSDN Online team managing the Windows Vista and Visual C++ developer centers. Before being employed at Microsoft, I was awarded MVP status for the Visual C++ product. A 20+ year veteran of programming with various languages - C++, C, Assembler, RPG III/400, PL/I, etc. - I've also written many technical books (Inside C#, Extending MFC Applications with the .NET Framework, Visual C++.NET Bible, etc.) and 100+ online articles.

Downloads

Comments

  • Simple

    Posted by fistagon on 04/17/2006 10:53am

    If you've already got your month/day/year split apart and you want to check for proper day/month combos

    Try this:

    Public Function CheckDate(ByVal strMonth As String, ByVal strDay As String, ByVal strYear As String) As Boolean
    strMonth = strMonth.Trim("0")
    strDay = strDay.Trim("0")
    Try
    Dim dt As New DateTime(strYear, strMonth, strDay)
    return true
    Catch ex As Exception
    return false
    End Try

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Lenovo recommends Windows 8 Pro. "I dropped my laptop getting out of the taxi." This probably sounds familiar to most IT professionals. If your employees are traveling, you know their devices are in for a rough go. Whether it's a trip to the conference room or a convention out of town, any time equipment leaves a user's desk it is at risk of being put into harm's way. Stay connected at all times, whether at the office or on the go, with agile, durable, and flexible devices like the Lenovo® …

  • U.S. companies are desperately trying to recruit and hire skilled software engineers and developers, but there is simply not enough quality talent to go around. Tiempo Development is a nearshore software development company. Our headquarters are in AZ, but we are a pioneer and leader in outsourcing to Mexico, based on our three software development centers there. We have a proven process and we are experts at providing our customers with powerful solutions. We transform ideas into reality.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date