Click here to Skip to main content
15,867,686 members
Articles / Programming Languages / C#
Tip/Trick

Validating dates in dd-MMM-yyyy format

Rate me:
Please Sign up or sign in to vote.
3.35/5 (9 votes)
3 Jul 2011CPOL 27.9K   9   2
using System.Text.RegularExpressionsprivate void fnValidateDateFormat(string strStartDate,string strEndDate){ Regex regexDt = new...
C#
using System.Text.RegularExpressions

private void fnValidateDateFormat(string strStartDate,string strEndDate)
{
	Regex regexDt = new Regex("(^(((([1-9])|([0][1-9])|([1-2][0-9])|(30))\\-([A,a][P,p][R,r]|[J,j][U,u][N,n]|[S,s][E,e][P,p]|[N,n][O,o][V,v]))|((([1-9])|([0][1-9])|([1-2][0-9])|([3][0-1]))\\-([J,j][A,a][N,n]|[M,m][A,a][R,r]|[M,m][A,a][Y,y]|[J,j][U,u][L,l]|[A,a][U,u][G,g]|[O,o][C,c][T,t]|[D,d][E,e][C,c])))\\-[0-9]{4}$)|(^(([1-9])|([0][1-9])|([1][0-9])|([2][0-8]))\\-([F,f][E,e][B,b])\\-[0-9]{2}(([02468][1235679])|([13579][01345789]))$)|(^(([1-9])|([0][1-9])|([1][0-9])|([2][0-9]))\\-([F,f][E,e][B,b])\\-[0-9]{2}(([02468][048])|([13579][26]))$)");

	Match mtStartDt = Regex.Match(strStartDate,regexDt.ToString());
	Match mtEndDt 	= Regex.Match(strEndDate,regexDt.ToString());
	if (mtStartDt.Success && mtEndDt.Success)
	{
      		//piece of code
	}
}

Above regular expression is specific to dates in dd-MMM-yyyy format. In case you are using more than 1 date format across your application, it would be a good idea to declare either a switch case that returns specific regex objects as per date formats or enums.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMinimally, if you're not going to go with Luc's suggestion, ... Pin
TheyCallMeMrJames18-May-10 8:02
TheyCallMeMrJames18-May-10 8:02 
GeneralRe: Minimally, if you're not going to go with Luc's suggestion, ... Pin
PIEBALDconsult4-Jun-12 16:08
mvePIEBALDconsult4-Jun-12 16:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.