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" />
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" />