dotnetco.de

Use CustomValidator to check textbox depending on Radiobutton

For input validation I often use the Validators provided by Microsoft out of the box: RequiredFieldValidator to check whether user entered some data into the textbox, RangeValidator to check the range of numeric values or dates, RegularExpressionValidator to check the size of user input (and much more of course), CompareValidator to check dates, and today I had to use CustomValidator to check one field depending on another field.
My asp.net application contains a textbox which has to be filled if the user selected ‘Yes’ on a radiobutton. The RequiredFieldValidator does not help because you could not add a condition there. So it has to be done with the CustomValidator. I’ve searched around and finally combined several sources into this solution so here is a complete overview how to set up.

Have a look at my RadioButton. Nothing special here.

<asp:RadioButtonList ID="MyBtn" runat="server" RepeatDirection="Horizontal">
 <asp:ListItem Value="Yes" />
 <asp:ListItem Value="No" />
</asp:RadioButtonList>

 

And the corresponding Textbox is here:

<asp:TextBox ID="MyTxtBox" runat="server" />

 

As I want to do the validation in the client we have to do some Javascript here.

<script type="text/javascript">
 function validateMyBtn(oSrc, args){
   var rbtnValue = null;
   var rbtnList = document.getElementsByName('<%= MyBtn.ClientID %>');
   var radio = rbtnList[0].getElementsByTagName("input");
   for (var j = 0; j < radio.length; j++) {
     if (radio[j].checked)
      rbtnValue = radio[j].value;
    }
     if (rbtnValue == 'Yes') {
      args.IsValid = !(args.Value == "")
    } else {
       args.IsValid = true;
    }
  }
</script>

 

This little JavaScript loops through all options to find out which one is checked. (Therefor of course it makes sense to ensure that at least one option is selected, e.g. by setting a default option or using a RequiredFieldValidator.) The value of the selected option is then compared. If it’s not “Yes” the validation always returns “true” because the textbox is only mandatory if option “Yes” is selected. If it’s “Yes” the value is checked whether it’s empty. I was surprised about ‘args.Value’: ‘args’ is given by the CustomValidator, it’s the “ControlToValidate”.

Here is the CustomValidator Definition:

<asp:CustomValidator ID="MyTxtBoxValidator" runat="server"
  ControlToValidate="MyTxtBox" ValidateEmptyText="true"
  ErrorMessage="Please enter some values into Textbox"
  ClientValidationFunction="validateMyBtn">
</asp:CustomValidator>

 

Take care about the property “ValidateEmptyText”: If you miss this one, the validation is always “true” for empty fields….Just to have it complete, here is the RequiredFieldValidator for the radiobutton:

<asp:RequiredFieldValidator ID="MyBtnValidator"
  ControlToValidate="MyBtn" runat="server"
  ErrorMessage="Please make your choice" SetFocusOnError="true" />

That’s it!

Leave a Comment