C# date validation

There is no direct built-in function or method to validate DateTime Data Type in C#. This following self-explanatory code snippet shows a method that takes string as argument and validates it using ParseExact Method of DateTime. Moreover, you can choose any Date Format / Style for validation.


private Boolean validateDate(string businessDate)
{
  Boolean dateValidationResult = true;
  try
  {
    IFormatProvider culture = new CultureInfo("fr-FR",true);
    DateTime.ParseExact(businessDate, "dd/MM/yyyy", culture);
  }
  catch (Exception exceptionObject)
  {
    dateValidationResult = false;
  }
  return dateValidationResult;
}


You can use it in this way to validate Date.


if (this.validateDate(businessDateTextBox.Text)== false)
{
  MessageBox.Show("Please write Accurate Business Date");
  businessDateTextBox.Focus();
  validationResult = false;        
}

Thanks
A Rahim Khan

Advertisements
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: