namespace YourNamespace
{
public class RadComboBoxSelectedValueValidator : CustomValidator
{
///
/// Gets or sets Empty message. If set and validator is not required, there will be no validation.
///
public string EmptyMessage
{
get;set;
}
///
/// Gets or sets the value if validator is required.
///
private bool _isRequired = true;
public bool IsRequired
{
get
{
return _isRequired;
}
set
{
_isRequired = value;
}
}
private const string clientFunctionName = "RadComboBox_ValidateSelectedValue";
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (IsRequired)
this.ServerValidate += new ServerValidateEventHandler(RadComboBoxSelectedValueValidator_ServerValidate);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
this.EnableClientScript = true;
this.ValidateEmptyText = true;
this.ClientValidationFunction = clientFunctionName;
string jsValidateSelectedValue = String.Empty;
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);
}
JavascriptUtility.RegisterClientScriptBlock(this, typeof(string), clientFunctionName, jsValidateSelectedValue, true);
}
private void RadComboBoxSelectedValueValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
args.IsValid = !String.IsNullOrEmpty(((RadComboBox)this.NamingContainer.FindControl(this.ControlToValidate)).SelectedValue);
}
}
}