In this post I will describe how to implement a simple validator for Telerik RadComboBox control. It includes a few useful ASP.NET techniques for both client and server side validation.
Problem
"Auto-complete" is a great feature provided by RadComboBox control which can make things easier when you need to work with the large amount of data. Users can start typing inside combo box, and appropriate items simply show up in a dropdown list. A typical scenario that requires this functionality involves selecting zip codes in your data entry screens. However, you might enter a wrong item and this is the situation where a validator should kick in.
Implementation
We will go through the basic steps - as always, we will start by inheriting from custom validator.
public
class
RadComboBoxSelectedValueValidator : CustomValidator
{
}
We will also expose a few properties: EmptyMessage and IsRequired, write some JavaScript for client validation and check data on the server.
Javscript code:
if
(IsRequired)
{
jsValidateSelectedValue = String.Format(@"function {0}(sender, args) {{
args.IsValid =
false
;
var combo = $find(sender.controltovalidate);
var text = combo.get_text();
if
(text.length > 0)
if
(combo.findItemByText(text))
args.IsValid =
true
;
}}", clientFunctionName);
}
else
{
jsValidateSelectedValue = String.Format(@"function {0}(sender, args) {{
args.IsValid =
false
;
var combo = $find(sender.controltovalidate);
var text = combo.get_text();
if
(text ==
'{1}'
)
{{
args.IsValid =
true
;
}}
else
{{
if
(text.length > 0)
if
(combo.findItemByText(text))
args.IsValid =
true
;
else
args.IsValid =
false
;
else
args.IsValid =
true
;
}}
}}", clientFunctionName, EmptyMessage);
}
Depending on 'IsRequired' property we will define validation logic. The last step is to perform server validation when 'IsRequired' property is set.
private
void
RadComboBoxSelectedValueValidator_ServerValidate(
object
source, ServerValidateEventArgs args)
{
args.IsValid =
!String.IsNullOrEmpty(((RadComboBox)
this
.NamingContainer.FindControl(
this
.ControlToValidate)).SelectedValue);
}
Here is how we use our custom validator:
<
telerik:RadComboBox
ID
=
"cboData"
runat
=
"server"
EnableLoadOnDemand
=
"true"
AllowCustomText
=
"false"
MarkFirstMatch
=
"true"
Width
=
"100%"
>
<
WebServiceSettings
Path
=
"PathToService"
Method
=
"LoadData"
/>
</
telerik:RadComboBox
>
<
Test:RadComboBoxValidator
ID
=
"vld"
runat
=
"server"
ControlToValidate
=
"cboData"
Text
=
"!"
SetFocusOnError
=
"true"
Display
=
"Dynamic"
>
</
Test:RadComboBoxValidator
>
You might want to set ValidationGroup and Error message properties. I am attaching the complete source code to this post - I hope you will find it helpful.