Skip navigation

Validate Date Input

Use the DateValidator class to validate user-entered dates quickly and easily.

Hot Tip

LANGUAGES: C#

TECHNOLOGIES: DateValidator class

 

Validate Date Input

Use the DateValidator class to validate user-entered dates quickly and easily.

 

By Jeff Prosise

 

Need to validate dates entered by users to ensure the dates are valid - even if they fall in leap years? Try the handy DateValidator class:

 

// Feb. 29, 1999

Bool isValid = DateValidator.IsDateValid (1999, 2, 29);

 

This class exposes a static method named IsDateValid that accepts a year, month, and day as input and returns true or false to indicate whether the specified date is valid. Calling it the previous way returns false. But calling it this way returns true because 2000 was a leap year:

 

// Feb. 29, 2000

Bool isValid = DateValidator.IsDateValid (2000, 2, 29);

 

IsDateValid gets its smarts from the .NET Framework's DateTime type, which throws an ArgumentOutOfRangeException if you attempt to construct a DateTime object around an invalid date:

 

class DateValidator

{

    public static bool IsDateValid (int year, int month, int day)

    {

        try {

            DateTime date = new DateTime (year, month, day);

            return true;

        }

        catch (ArgumentOutOfRangeException) {

            return false;

        }

    }

}

 

Jeff Prosise is author of several books, including Programming Microsoft .NET (Microsoft Press). He also is a co-founder of Wintellect (http://www.wintellect.com), a software consulting and education firm that specializes in .NET. Got a question for this column? Submit queries to [email protected].

 

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish