External DatePicker Controls can be useful, and the ComponentArt sure is, except for the annoying lack of client-side validation. Nevertheless, its not too hard to integrate your own javascript and validate your date entries.
This sample uses Prototype, but you can simply replace the '$' by 'document.getElementById' and you should be okay.
(This also assumes you have encapsulated your date picker in a user control)
1.Add a (hidden) div element to your user control
<div style="display:none" id="validationdiv<%=ClientID%>">
<asp:TextBox ID="ValidationTextBox" runat="server" EnableViewState="false"></asp:TextBox>
</div>
2. Add a RequiredFieldValidator, pointing to our hidden TextBox
<asp:RequiredFieldValidator Enabled="false" ID="dateValidator" ControlToValidate="ValidationTextBox" runat="server" ErrorMessage="***" Display="None"></asp:RequiredFieldValidator>
3.Expand your javascript handlers, to change your textbox values when the Calendar/Picker values change.
function MarkAsValidationOk<%=ClientID%>()
{
$('<%=ValidationTextBox.ClientID%>').value = true;
}
function MarkAsValidationNOk<%=ClientID%>()
{
$('<%=ValidationTextBox.ClientID%>').value = “”;
}
function Picker1_onSelectionChanged(sender, eventArgs)
{
sender.AssociatedCalendar.setSelectedDate(sender.getSelectedDate());
MarkAsValidationOk<%=ClientID%>()}
function Calendar_OnSelectionChanged(calendar)
{
calendar.AssociatedPicker.SetSelectedDate(calendar.GetSelectedDate());
MarkAsValidationOk<%=ClientID%>()}
function ClearCalendar<%= Calendar1.ClientObjectId %>()
{
<%= Calendar1.ClientObjectId %>.ClearSelectedDate();
<%= Picker1.ClientObjectId %>.ClearSelectedDate();
MarkAsValidationNOk<%=ClientID%>()
}
4. Add some configuration settings to your user control Codebehind.
public bool EnableValidation { set { dateValidator.Enabled = value; } }
public string ValidationErrorMessage { set { dateValidator.ErrorMessage = value; } }
public string ValidationGroup { set { dateValidator.ValidationGroup = value; } }
5. Expand your 'setdate' server-side functionality to flag validation as ok.
public void SetDate(DateTime date)
{
Calendar1.SelectedDate = date;
Picker1.SelectedDate = date;
timeSelectorControl.DefaultHour = date.Hour;
timeSelectorControl.DefaultMinute = date.Minute;
Page.ClientScript.RegisterStartupScript(GetType(), "datejs" + ClientID, "MarkAsValidationOk" + ClientID + "();", true);
}
6. All done, now you can simply enable validation by setting some properties in the page that uses your control:
<uc1:CalendarPicker ID="birthdayPicker" EnableValidation="true" ValidationGroup="EmployeeValidationGroup" ValidationErrorMessage="BirthDate_Required" runat="server" ShowTimePart="false" />
No comments:
Post a Comment