Q
Problem solve Get help with specific problems with your technologies, process and projects.

How do I validate a field according to an option selected in a listbox?

My question is about how to validate (using a custom validator) a field according to an option selected in a listbox. Let's say, if the user select option1 (in the listbox), it won't be necessary to validate the filed "Name," but if the user choose option2, then it will be necessary to enter a name.
You can create a custom validator and add a second property to point to the listbox. Then, you should override the EvaluateIsValid method or attach to the base ServerValidate event, and perform the logic to retrieve the list value and validate accordingly. The validator code is something along the lines:

public class MyValidator : CustomValidator
{
 public MyValidator()
 {
  //Attach to the server validation event.
  this.ServerValidate +=
   new ServerValidateEventHandler
(MyValidator_ServerValidate);
 }

 [DefaultValue("")]
 [TypeConverter(typeof(ValidatedControlConverter))]
 [Category("Behavior")]
 public string ListControlToValidate 
 { 
  get { return ViewState["ListControlToValidate"] as String; } 
  set { ViewState["ListControlToValidate"] = value; }
 }

 private void MyValidator_ServerValidate(object source,
  ServerValidateEventArgs args)
 {
  //Retrieve the list control
  if (ListControlToValidate.Length > 0)
  {
   string listvalue = base.GetControlValidationValue
(ListControlToValidate);
   // Do whatever
   if (listvalue == "Customer")
   {
    string textvalue = 
base.GetControlValidationValue(ControlToValidate);
    if (textvalue.Length == 0)
     return false;
    else
     return true;
   }
  }
  
  // Assume that if we didn't have a list to validate, we're
valid.
  return true;
 }
}

Note the attributes on ListControlToValidate. They will help make the new property more IDE-friendly, as it will show up in the property browser in the same category as the ControlToValidate, and will also have the dropdown for control selection, thanks to the TypeConverter attribute.

As the logic isn't particularly complex, you should also provide a JavaScript function to perform this validation on the client side also, thus improving the responsiveness of your application. For that purpose, you can override the OnPreRender method to emit the necessary script. As the only thing that will change on the script between validators are the control IDs to check, we can store it on a static variable with the placeholders ready for replacement:

  //Implement the same server-side logic in javascript.
  static string _script = @"
<script language='Javascript'>
function MyValidatorFunction(source, args)
{
  args.IsValid = true;

 var listvalue = document.getElementById('{0}').value.toString();
 // Do whatever
 if (listvalue == 'Customer')
 {
  var textvalue = document.getElementById('{1}').value.toString
();
  if (textvalue.length == 0)
   args.IsValid = false;
  else
   args.IsValid = true;
 }
}
</script>
";

Note that the logic should be as close as possible to the server-side version. The base class offers some helper methods such as the previously shown GetControlValidationValue to deal with controls. We can use another method in our OnPreRender method as well, where we will register the script and replace the control ids inside it:

protected override void OnPreRender(EventArgs e)
{
 base.OnPreRender (e);
 if (ListControlToValidate.Length != 0)
 {
  Page.RegisterClientScriptBlock(this.ClientID, 
   String.Format(_script, 
    base.GetControlRenderID
(ListControlToValidate), 
    base.GetControlRenderID(ControlToValidate)));
 }
}

Finally, should we want to hide the ClientValidationFunction and forbid the user from changing it, we could do like that too:

[Browsable(false)]
public new string ClientValidationFunction 
{ 
 get { return "MyValidatorFunction"; }
 set { } //Do nothing as we don't want the user to change this.
}

That gives your validation control user the most familiar interface yet you remain under control of what's going on.

Dig Deeper on .NET tutorials, guides and quizzes

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.

-ADS BY GOOGLE

SearchCloudComputing

SearchSoftwareQuality

TheServerSide.com

SearchCloudApplications

Close