Click here to Skip to main content
15,891,529 members
Articles / Web Development / IIS

Date control with support for languages and different date formats

Rate me:
Please Sign up or sign in to vote.
4.14/5 (11 votes)
31 May 20054 min read 93.6K   713   47  
Using .NET's System.Globalization class for retrieving month names in forgein lanaguages, and the DateTimeFormatInfo for keeping your dates the correct way around.
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace i386.UI
{
	/// <summary>
	/// TextBoxDateTimeValidator - authored by Gavin Lyons i386.com
	/// current only performs validation on UK Dateformat 
	/// </summary>
	[ToolboxData("<{0}:TextBoxDateTimeValidator runat=server ErrorMessage=\"TextBoxDateTimeValidator\"></{0}:TextBoxDateTimeValidator>")]
	public class TextBoxDateTimeValidator: BaseCompareValidator
	{
		

		[Bindable(true), 
		Description("TextBoxDateTimeValidator_AllowBlankEntry"), 
		Category("Behavior"), 
		DefaultValue(true)]
		public  bool AllowBlankEntry
		{
			get
			{
				object AllowBlankEntryVS = this.ViewState["AllowBlankEntry"];
				if (AllowBlankEntryVS != null)
				{
					return (bool) AllowBlankEntryVS;
				}
				return true;
			}
			set
			{
				this.ViewState["AllowBlankEntry"] = value;
			}
		}

		#region Overriden Methods
		/// <summary>
		/// Adds client-side functionality for uplevel browsers by specifying the JavaScript function
		/// to call when validating, as well as a needed parameter (the MaximumLength property value).
		/// </summary>
		protected override void AddAttributesToRender(HtmlTextWriter writer)
		{
			base.AddAttributesToRender(writer);
			if (base.RenderUplevel)
			{
				writer.AddAttribute("evaluationfunction", "TextBoxDateTimeValidatorIsValid");
				writer.AddAttribute("allowblankentry", this.AllowBlankEntry.ToString());
			}
		}

		/// <summary>
		/// Checks to ensure that the ControlToValidate property is set to a TextBox
		/// </summary>
		protected override bool ControlPropertiesValid()
		{
			if (base.FindControl(base.GetControlRenderID(base.ControlToValidate)).GetType() != new System.Web.UI.WebControls.TextBox().GetType())
				throw new HttpException("Control to Validate of must be a text box.");
			return base.ControlPropertiesValid();
		}

		/// <summary>
		/// Performs the server-side validation.  If MaximumLength is less than 0, always returns True;
		/// otherwise, returns True only if the ControlToValidate's length is less than or equal to the
		/// specified MaximumLength.
		/// </summary>
		protected override bool EvaluateIsValid()
		{
			string ControlToValidateName = base.GetControlValidationValue(base.ControlToValidate);
			// TextBox is empty and AllowBlankEntry is true
			if (this.AllowBlankEntry && (ControlToValidateName=="")) return true;
			return IsDate(ControlToValidateName);
		}
		protected bool IsDate(string value) 
		{
			try
			{
				DateTime.Parse(value);
				return(true);
			}
			catch
			{
				return(false);
			}
		} 
		/// <summary>
		/// Injects the JavaScript function that performs client-side validation for uplevel browsers.
		/// </summary>
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);
			if (base.RenderUplevel)
				Page.RegisterClientScriptBlock("TxtBxDteTmeValIsValid", 
					@"<script language=""Javascript"">
					function TextBoxDateTimeValidatorIsValid(val)
					{
						var Value = ValidatorGetValue(val.controltovalidate);	
						var Adi=Value.split('/');if (Adi.length==3){var yydi= Adi[2].split(' ');
						if (yydi.length==2) return (isValidDate(Adi[0],Adi[1],yydi[0]) && TimeHHmm(yydi[1]));
						else return isValidDate(Adi[0],Adi[1],Adi[2]);	}
						else if (Value =='' && val.allowblankentry) return true; else return false;}
					function TimeHHmm(S) { return /^(24):(00)|([01][0-9]|2[0-3]):([0-5][0-9])$/.test(S) }
					function isValidDate(day,month,year){if (month==0) month--;if (month>0 && month<13) month--;
					var dteDate;dteDate=new Date(year,month,day);
					return ((day==dteDate.getDate()) && (month==dteDate.getMonth()) && (year==dteDate.getFullYear()));}
					</script>");

		}
		#endregion
	}
}


namespace i386.UI
{
	/// <summary>
	/// TextBoxLengthValidator - authored by Jisun Lee.
	/// </summary>
//http://aspnet.4guysfromrolla.com/articles/112404-1.aspx
	[ToolboxData("<{0}:TextBoxLengthValidator runat=server ErrorMessage=\"TextBoxLengthValidator\"></{0}:TextBoxLengthValidator>")]
	public class TextBoxLengthValidator : BaseCompareValidator
	{
		/// <summary>
		/// Specifies the maximum length of the TextBox the control is validating.  If this value
		/// is less than 0, then inputs of any length are considered valid.
		/// </summary>
		[Bindable(true), 
		Description("TextBoxLengthValidator_MaximumLength"), 
		Category("Behavior"), 
		DefaultValue(-1)]
		public int MaximumLength
		{
			get
			{
				object MaxLengthVS = this.ViewState["MaximumLength"];
				if (MaxLengthVS != null)
				{
					return (int) MaxLengthVS;
				}
				return -1;
			}
			set
			{
				this.ViewState["MaximumLength"] = value;
			}
		}
 
		#region Overriden Methods
		/// <summary>
		/// Adds client-side functionality for uplevel browsers by specifying the JavaScript function
		/// to call when validating, as well as a needed parameter (the MaximumLength property value).
		/// </summary>
		protected override void AddAttributesToRender(HtmlTextWriter writer)
		{
			base.AddAttributesToRender(writer);
			if (base.RenderUplevel)
			{
				writer.AddAttribute("evaluationfunction", "TextBoxLengthValidatorIsValid");
				writer.AddAttribute("maximumlength", this.MaximumLength.ToString());
			}
		}

		/// <summary>
		/// Checks to ensure that the ControlToValidate property is set to a TextBox
		/// </summary>
		protected override bool ControlPropertiesValid()
		{
			if (base.FindControl(base.GetControlRenderID(base.ControlToValidate)).GetType() != new System.Web.UI.WebControls.TextBox().GetType())
				throw new HttpException("Control to Validate of must be a text box.");

			return base.ControlPropertiesValid();
		}

		/// <summary>
		/// Performs the server-side validation.  If MaximumLength is less than 0, always returns True;
		/// otherwise, returns True only if the ControlToValidate's length is less than or equal to the
		/// specified MaximumLength.
		/// </summary>
		protected override bool EvaluateIsValid()
		{
			if (this.MaximumLength < 0)
				return true;

			string ControlToValidateName = base.GetControlValidationValue(base.ControlToValidate);

			return ControlToValidateName.Length <= System.Convert.ToInt32(this.MaximumLength);
		}

		/// <summary>
		/// Injects the JavaScript function that performs client-side validation for uplevel browsers.
		/// </summary>
		protected override void OnPreRender(EventArgs e)
		{
			base.OnPreRender(e);

			if (base.RenderUplevel)
				Page.RegisterClientScriptBlock("TxtBxLngthValIsValid", 
					@"<script language='javascript'>
					function TextBoxLengthValidatorIsValid(val) 
					{ 
						var value = ValidatorGetValue(val.controltovalidate); 
						if (ValidatorTrim(value).length == 0) return true; 
						if (val.maximumlength < 0) return true; 
						return (value.length <= val.maximumlength);
					}
				</script>");
		}
		#endregion
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
Austria Austria
Programmer, Cook, Photographer I guess that's me.

http://www.i386.com

http://blog.glyons.at

Comments and Discussions