I am working on this DatePicker control which I found on the web, I am trying to customize it to my needs with Client Validation, but it is not working, could you please fix it for me?
this is the datepicket and it works fine.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomControls
{
[DefaultProperty("Text"), ValidationProperty("Value")]
[ToolboxData("<{0}:DatePicker runat=server />")]
public class DatePicker : CompositeControl, IPostBackDataHandler
{
#region Private Fields
// The dropdownlists to render on the page
private System.Web.UI.WebControls.DropDownList dayList;
private System.Web.UI.WebControls.DropDownList yearList;
private System.Web.UI.WebControls.DropDownList monthList;
// The arrays used to populate the drop down lists
// The blanks at the beginning are for a blank item in the list box
private string[] DayArray = { "", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15",
"16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" };
private string[] MonthArray = { "", "January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December" };
private string[] YearArray;
private static readonly object EventControlChanged = new object();
#endregion
#region Properties
[
Bindable(true),
Category("Misc"),
Themeable(true),
Description("Sets/Gets the Value of the Date control")
]
public string Value
{
get
{
string s = (string)ViewState["Value"];
if (s == null)
return String.Empty;
else
return s;
}
set
{
this.SetSelected(value);
ViewState["Value"] = value;
}
}
// Returns selected day
private int SelectedDay
{
get
{
if (ViewState["SelectedDay"] == null)
return -1;
else
return (int)ViewState["SelectedDay"];
}
set
{
ViewState["SelectedDay"] = value;
}
}
// Returns selected month
private int SelectedMonth
{
get
{
if (ViewState["SelectedMonth"] == null)
return -1;
else
return (int)ViewState["SelectedMonth"];
}
set
{
ViewState["SelectedMonth"] = value;
}
}
// Returns selected year
private int SelectedYear
{
get
{
if (ViewState["SelectedYear"] == null)
return -1;
else
return (int)ViewState["SelectedYear"];
}
set
{
ViewState["SelectedYear"] = value;
}
}
// When this property is true, set the control's value to the current date
[
Bindable(true),
Category("Misc"),
Themeable(true),
Description("Says wether to set the initial value to the current day")
]
public bool SelectCurrentDate
{
get
{
if (ViewState["SelectCurrentDate"] == null)
return true; // Default value of true
return (bool)ViewState["SelectCurrentDate"];
}
set
{
ViewState["SelectCurrentDate"] = value;
bool _setCurrent = value;
if (_setCurrent)
this.Value = DateTime.Today.ToShortDateString();
}
}
// Number of years in the past to display
[
Bindable(true),
Category("Misc"),
Themeable(true),
Description("Sets/Gets the years to display in the past")
]
public int YearsBack
{
get
{
if (ViewState["YearBack"] == null)
return 10; // Default value of 10 years
return (int)ViewState["YearsBack"];
}
set
{
ViewState["YearsBack"] = value;
}
}
// Number of years in the future to display
[
Bindable(true),
Category("Misc"),
Themeable(true),
Description("Sets/Gets the years to display in the future")
]
public int YearsForward
{
get
{
if (ViewState["YearsForward"] == null)
return 10; // Default value of 10 years
return (int)ViewState["YearsForward"];
}
set
{
ViewState["YearsForward"] = value;
}
}
#endregion
#region Event Handler
// Remove/Add handler to event
public event EventHandler Changed
{
add
{
Events.AddHandler(EventControlChanged, value);
}
remove
{
Events.RemoveHandler(EventControlChanged, value);
}
}
// Fired when RaisePostDataChangedEvent()
protected virtual void OnChanged(EventArgs e)
{
EventHandler ControlChanged = (EventHandler)Events[EventControlChanged];
if (ControlChanged != null)
ControlChanged(this, e);
}
#endregion
#region Overriden Method
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (Page != null)
Page.RegisterRequiresPostBack(this);
}
#endregion
#region Helper Methods
// Take the value, and set the selected values of the
private void SetSelected(string When)
{
string[] ResultList;
Regex DateSplitter = new Regex("^\\d{1,2}\\/\\d{1,2}\\/\\d{4}$");
if (DateSplitter.IsMatch(When)) //The date has a good format
{
char divider = '/';
ResultList = When.Split(divider);
SelectedMonth = Int32.Parse(ResultList[0]);
SelectedDay = Int32.Parse(ResultList[1]);
SelectedYear = Int32.Parse(ResultList[2]);
}
else //When must be empty or not recognizable, so set the listboxes to the empty value
{
SelectedDay = -1;
SelectedMonth = -1;
SelectedYear = -1;
}
}
#endregion
#region Create Control Components
// Create the controls
protected override void CreateChildControls()
{
// Clear out the control hiearchy
Controls.Clear();
// see if we need to build up the hierarchy
if (ViewState["ControlCount"] == null)
CreateControlHierarchy();
}
protected void CreateControlHierarchy()
{
int nYear;
int i;
//Create the days dropdown list, fill with array declared above
dayList = new System.Web.UI.WebControls.DropDownList();
dayList.SelectedIndex = this.SelectedDay;
dayList.ID = "Day";
dayList.DataSource = DayArray;
dayList.DataBind();
this.Controls.Add(dayList);
//Create the months dropdown list, fill with array declared above
monthList = new System.Web.UI.WebControls.DropDownList();
monthList.SelectedIndex = this.SelectedMonth;
monthList.ID = "Month";
monthList.DataSource = MonthArray;
monthList.DataBind();
this.Controls.Add(monthList);
//Fill years array based on the number of years back that was specified by the user
YearArray = new string[this.YearsBack + this.YearsForward + 2]; //1 extra=blank item in list
yearList = new System.Web.UI.WebControls.DropDownList();
nYear = DateTime.Now.Year;
YearArray[0] = "";
for (i = 1; i <= YearArray.GetUpperBound(0); i++)
{
if ( i <= this.YearsBack )
YearArray = Convert.ToString(nYear - this.YearsBack + (i - 1));
else
YearArray = Convert.ToString(nYear + (i-this.YearsForward-1));
// Add last year
YearArray[YearArray.Length-1] = Convert.ToString(nYear + this.YearsForward);
if (YearArray == Convert.ToString(this.SelectedYear))
{
//Set the selected index if a match is found
yearList.SelectedIndex = i;
}
}
yearList.ID = "Year";
yearList.DataSource = YearArray;
yearList.DataBind();
this.Controls.Add(yearList);
}
#endregion
#region Load Posted Data
bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection)
{
int Day = 0;
int Month = 0;
int Year = 0;
bool Changed = false;
string postedDay = postCollection[this.UniqueID.ToString() + "$Day"];
string postedMonth = postCollection[this.UniqueID.ToString() + "$Month"];
string postedYear = postCollection[this.UniqueID.ToString() + "$Year"];
if (!String.IsNullOrEmpty(postedDay))
{
Day = Int32.Parse(postedDay);
if (Day != this.SelectedDay)
{
this.SelectedDay = Day;
Changed = true;
}
}
else
{
if (this.SelectedDay != -1)
{
this.SelectedDay = -1;
Changed = true;
}
}
if (!String.IsNullOrEmpty(postedMonth))
{
Month = Array.IndexOf(this.MonthArray, postedMonth);
if (Month != this.SelectedMonth)
{
this.SelectedMonth = Month;
Changed = true;
}
}
else
{
if (this.SelectedMonth != -1)
{
this.SelectedMonth = -1;
Changed = true;
}
}
if (!String.IsNullOrEmpty(postedYear))
{
Year = Int32.Parse(postedYear);
if (Year != this.SelectedYear)
{
this.SelectedYear = Year;
Changed = true;
}
}
else
{
if (this.SelectedYear != -1)
{
this.SelectedYear = -1;
Changed = true;
}
}
if (this.SelectedDay == -1 || this.SelectedMonth == -1 || this.SelectedYear == -1)
this.Value = "";
else
this.Value = this.SelectedMonth.ToString() + "/" + this.SelectedDay.ToString() + "/" + this.SelectedYear.ToString();
return Changed;
}
void IPostBackDataHandler.RaisePostDataChangedEvent()
{
this.OnChanged(EventArgs.Empty);
}
#endregion
}
}
Here is the validator:
using System;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomControls
{
public class DatePickerValidator : BaseValidator
{
#region Private Fields
#endregion
protected override bool EvaluateIsValid()
{
string Value = this.GetControlValidationValue(this.ControlToValidate);
return this.IsValidDate(Value);
}
private bool IsValidDate(string Item)
{
// to be built later
}
protected override void AddAttributesToRender(HtmlTextWriter writer)
{
if (this.DetermineRenderUplevel() && this.EnableClientScript)
{
base.AddAttributesToRender(writer);
writer.AddAttribute("controltovalidate", this.ControlToValidate);
writer.AddAttribute("evaluationfunction", "DatePickerIsValid");
writer.AddAttribute("display", this.Display.ToString());
writer.AddAttribute("style", "display:none");
writer.AddAttribute("errormessage", this.ErrorMessage);
}
}
protected override void OnPreRender(EventArgs e)
{
// MS Standard JavaScript File to include
base.OnPreRender(e);
if (this.DetermineRenderUplevel() && this.EnableClientScript)
{
this.SetClientScript();
}
}
protected void SetClientScript()
{
StringBuilder script = new StringBuilder();
script.Append("var errorType = 0;\r");
script.Append("function DatePickerIsValid(val)\r");
script.Append("{\r");
script.Append("var CtrlToValidate = val.controltovalidate;\r");
script.Append("var day = document.getElementById(CtrlToValidate + \"_Day\").value;\r");
script.Append("var month = document.getElementById(CtrlToValidate + \"_Month\").value;\r");
script.Append("var day = document.getElementById(CtrlToValidate + \"_Year\").value;\r");
script.Append("\r");
script.Append("var sExec = \"var bReturn = CheckDate(day,month,year);\"\r");
script.Append("eval(sExec);\r");
script.Append("\r");
script.Append("if ( !bReturn )\r");
script.Append("{\r");
script.Append("val.innerHTML = displayError(errorType, CtrlToValidate);\r");
script.Append("}\r");
script.Append("else\r");
script.Append("{\r");
script.Append("val.innerHTML = \"\";\r");
script.Append("}\r");
script.Append("val.errormessage = val.innerHTML;\r");
script.Append("return bReturn;\r");
script.Append("}\r");
script.Append("function isEmpty(aTextValue)\r");
script.Append("{\r");
script.Append("if ((aTextValue.length==0) || (aTextValue==null))\r");
script.Append("return true;\r");
script.Append("\r");
script.Append("return false; \r");
script.Append("}\r");
script.Append("function CheckDate(day,month,year)\r");
script.Append("{\r");
script.Append("if ( isEmpty(day) || isEmpty(month) || isEmpty(year) )\r");
script.Append("{\r");
script.Append("errorType = 1;\r");
script.Append("return false;\r");
script.Append("}\r");
script.Append("var daysPerMonth = getDaysofYear(year);\r");
script.Append("monthIndex = GetMonthIndex(month);\r");
script.Append("if ( day > daysPerMonth[monthIndex] )\r");
script.Append("{\r");
script.Append("errorType = 3;\r");
script.Append("return false;\r");
script.Append("}\r");
script.Append("return true;\r");
script.Append("}\r");
script.Append("function GetMonthIndex(month)\r");
script.Append("{\r");
script.Append("if (month == \"January\")\r");
script.Append("return (1);\r");
script.Append("if (month == \"February\")\r");
script.Append("return (2);\r");
script.Append("if (month == \"March\")\r");
script.Append("return (3);\r");
script.Append("if (month == \"April\")\r");
script.Append("return (4);\r");
script.Append("if (month == \"May\")\r");
script.Append("return (5);\r");
script.Append("if (month == \"June\")\r");
script.Append("return (6);\r");
script.Append("if (month == \"July\")\r");
script.Append("return (7);\r");
script.Append("if (month == \"August\")\r");
script.Append("return (8);\r");
script.Append("if (month == \"September\")\r");
script.Append("return (9);\r");
script.Append("if (month == \"October\")\r");
script.Append("return (10);\r");
script.Append("if (month == \"November\")\r");
script.Append("return (11);\r");
script.Append("if (month == \"December\")\r");
script.Append("return (12);\r");
script.Append("}\r");
script.Append("function getDaysofYear(year)\r");
script.Append("{\r");
script.Append("if ( leapYear(year) == 1 )\r");
script.Append("Leap = 29;\r");
script.Append("else\r");
script.Append("Leap = 28;\r");
script.Append("\r");
script.Append("daysofYear = new Array(0,31,Leap,31,30,31,30,31,31,30,31,30,31);\r");
script.Append("\r");
script.Append("return (daysofYear);\r");
script.Append("}\r");
script.Append("\r");
script.Append("function leapYear(year)\r");
script.Append("{\r");
script.Append("if (((year%4)==0 && ((year%100)!=0) || ((year%400)==0))\r");
script.Append("return (1);\r");
script.Append("else\r");
script.Append("return (0);\r");
script.Append("} \r");
script.Append("function displayError(nType,sName)\r");
script.Append("{\r");
script.Append("if (nType == 1)\r");
script.Append("return 'Date Requried';\r");
script.Append("if (nType == 3)\r");
script.Append("return 'Invalid Date';\r");
script.Append("}\r");
this.Page.ClientScript.RegisterStartupScript(this.GetType(),"DateValidate",script.ToString());
}
}
}
Can you please help me?