how to do validation with regex for date field in C#

Advertisements

i want to validate the dates like ’22/07/22′. i want regex for this date value

code

regex= "^\d{6}$";

>Solution :

You are far better off using DateTime.TryParse

eg,

if(DateTime.TryParseExact(stringToValidate, "dd/MM/yy", CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime d)) 
{
   // got it right, d is now a valid DateTime 
}
else 
{
   // got it wrong....
}

This will ensure its a valid year / day and month combination. Taking into account things like leap years, different days in the months, etc.

If you need localized time you might want to use DateTimeOffset

Leave a ReplyCancel reply