Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C# code to validate a date value 1

Status
Not open for further replies.

meckeard

Programmer
Aug 17, 2001
619
US
Does anyone know how I can validate a date value in C#?

I goggled this and only found a solution using the DateTime.Parse method and trapping the error if it's not a valid date. But that's doesn't seem like a very efficient way to do it.

VB has IsDate()? Doesn't C# have something similar?

Thx.
 
Nope. No IsDate(). I think that somebody posted this here (a bit lengthy but you can use what you need. It looks like a mess here but if you copy/paste it into VS.NET it will format fine.
Code:
public bool ValidDate(string vDate) // ++++++++++ Checks to see if a date is valid +++++++
		{
			vDate = vDate.Trim();
			if (vDate == "")
				return false;
			int Mon, Day, Yr; 
			DateTime ValDate; 
			
			try
			{
				if (Regex.IsMatch(vDate,@"\d{1,2}[/]\d{1,2}[/](\d{4}|\d{2})") || 
					Regex.IsMatch(vDate,@"\d{1,2}[-]\d{1,2}[-](\d{4}|\d{4})"))  //looks for a format with 2 /'s or 2 -'s
				{
					ValDate = Convert.ToDateTime(vDate);
				}
				else
				{
					if (vDate.Trim().Length != 8) //Not a readable date format
						return false;

					if (Convert.ToInt16(vDate.Substring(0, 2)) > 12)  //Format yyyymmdd
					{
						Yr = Convert.ToInt16(vDate.Substring(0, 4));
						Mon = Convert.ToInt16(vDate.Substring(4, 2));
						Day = Convert.ToInt16(vDate.Substring(6, 2));
                        
						return (ValidDate(Mon.ToString() + "/" + Day.ToString() + "/" + Yr.ToString()));
                        
					}
					else //Format mmddyyyy
					{
						Mon = Convert.ToInt16(vDate.Substring(0, 2));
						Day = Convert.ToInt16(vDate.Substring(2, 2));
						Yr = Convert.ToInt16(vDate.Substring(4, 4));
                        
						return (ValidDate(Mon.ToString() + "/" + Day.ToString() + "/" + Yr.ToString()));
					}
				}
			}
			catch    //error is captured if the date cannot be established by C#'s Convert.ToDateTime()
			{
				return false;
			}

			return true;
		}
 
If it's just a date with no time, then use a CompareValidator with the operator set to DataTypeCheck and the type set to a date.

If you'd like to do something more customized, you can use a RegEx validator.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top