Custom Validator On DropdownList Control
|
|
|
|
|
.Net Framework Version: 1.0, 1.1, 2.0
Every now and then we get question from our users and clients about validating
values in DropdownList control on client side to avoid costly postback
and validate values on server side. There is a very simple solution to this
problem. There is a very handy dandy CustomValidator control that
can be used to validate any control on the page. There is one property of
validator controls where lot of developers get stuck is ControlToValidate.
This is where CustomValidator becomes handy. It does not require
that property to be set. And that makes it very useful to validate not just one
control but multiple control values.
Following code snipet shows simple javascript function that is used to validate
a DropdownList control selection.
function ValidateGenderSelection(source, arguments)
{
var genderList = document.getElementById("GenderDropDownList");
if (null != genderList)
{
var iValue = new Number(genderList[genderList.selectedIndex].value);
arguments.IsValid=(iValue > 0);
}
else
{
arguments.IsValid = false;
}
}
<asp:DropDownList ID="GenderDropDownList" runat="server"> />
<asp:CustomValidator ID="GenderSelectionRequiredValidator" runat=server
ClientValidationFunction="ValidateGenderSelection"
ErrorMessage="Select Gender" ForeColor="Red"
Display=Dynamic></asp:CustomValidator>
I have attached a very simple Visual Studio 2005 project which you can use to
see this script in action.
|