Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

code

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading