The problem them becomes how to validate the DropDownList on the client side such that if the user does not select an item other than the default "--Select One--" item a message is display.
I found a post that shows how to use the CustomValidator control to validate a DropDownList. The problem with this solution is that it does not take into account when a control is embedded within other controls that are tagged with the INamingContainer interface. This interface tells ASP.NET to automatically generate unique "id" attribute values on the ensuing HTML tags generated for a control. This unique id is prepended with the id of each parent control up to the root control. For example, a DropDownList embedded in a Panel control might have the id "ctl00$ddlMyDropDown". Therefore, in the solution mentioned above, we can't simply us "document.getElementById" Javascript function to locate the DropDownList control.
A better solution is to utilize the ControlToValidate property of the CustomValidator control. When this is set at design-time ASP.NET will generate Javascript code to add this value as an attribute of the validator control in the HTML DOM. For instance, looking at the source of the page I'm working on the following code is generated:
var ctl00_MainContent_CustomValidator1 = document.all ? document.all["ctl00_MainContent_CustomValidator1"] : document.getElementById("ctl00_MainContent_CustomValidator1");
ctl00_MainContent_CustomValidator1.controltovalidate = "ctl00_MainContent_ddlFeedbackType";
The property "controltovalidate" contains the fully-qualified unique id of the target control we're validating. We can use the "controltovalidate" property in our Javascript function that is used to validate the DropDownList:
function ValidateFeedbackType(source, arguments)
{
var ddl = document.getElementById(source.controltovalidate);
if (null != ddl)
{
var value = ddl[ddl.selectedIndex].value;
arguments.IsValid = (value != "00000000-0000-0000-0000-00000000000");
}
else
{
arguments.IsValid = false;
}
}
1 comment:
This was a helpful article. I will be implementing this validation soon. Thanks!
Post a Comment