C# ASP.Net Validate Date
Posted by in CSharp March 16, 2012 1 Comment

This is just a function written in ASP.NET (C#) that validates an input date (with format dd-MM-yyyy) to see if it’s valid. An message will be displayed for each case to indicate the result.

Actually, you can change a bit in the format and separator to validate the given date in other formats such as: dd/MM/yyy, MM-dd-yyyy, MM/dd/yyyy, etc.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class csharp_check_valid_date : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    public static bool isValidDate(string datePart, string monthPart, string yearPart)
    {
        DateTime date;
 
        string strDate = string.Format("{0}-{1}-{2}", datePart, monthPart, yearPart);
 
        if (DateTime.TryParseExact(strDate, "dd-MM-yyyy", System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.None, out date))
        {
            return true;
        }
        else
        {
            return false;
        }   
    }
    protected void btnValidate_Click(object sender, EventArgs e)
    {
        string date = txtDate.Text.Trim();
 
        try
        {
            string[] date_arr = date.Split('-');
 
            if (isValidDate(date_arr[0], date_arr[1], date_arr[2]))
            {
                lblMessage.Text = "The given date is VALID!";
            }
            else
            {
                lblMessage.Text = "The given date is NOT VALID!";
            }
        }
        catch(Exception ex)
        {
            lblMessage.Text = ex.Message.ToString();
        }
    }
}

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • Kenigarage

    Hi Hoan!
    Where is your company located?
    Thanks Hoan!