Search code examples
c#asp.netvalidationradiobuttonlist

ASP.Net: Validating Radio Button Input with C#


I'm running into issues creating a Custom Validator input for my radio button list. I've coded everything out and everything runs without a problem. It's just nothing happens when the validation is supposed to occur. My other validations work just fine.

Here's my HTML code:

<asp:RadioButtonList ID="SalaryPaidByEFT" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow" CssClass="width-100 radio">
    <asp:ListItem Text="Yes" Value="true"></asp:ListItem>
    <asp:ListItem Text="No" Value="false"></asp:ListItem>
    <asp:ListItem Text="Not Applicable" Value="null" Selected="True"></asp:ListItem>
</asp:RadioButtonList>
<asp:CustomValidator ID="cvSalaryPaidByEFT" runat="server"
    ErrorMessage="Salary Must Be Paid By EFT" ControlToValidate="SalaryPaidByEFT"
    OnServerValidate="cvSalaryPaidByEFT_ServerValidate" CssClass="has-error"
    Display="Dynamic"></asp:CustomValidator>

Here's my C# code:

protected void cvSalaryPaidByEFT_ServerValidate(object source, ServerValidateEventArgs args)
{
    args.IsValid = (this.SalaryPaidByEFT.SelectedIndex == 0);
}

Can anyone spot anything I may be missing to guide me to a solution?


Solution

  • Are you missing a call to the this.Validate() method and checking of IsValid property of the page.. From msdn example:

    if (this.IsPostBack)
    {
        this.Validate();
        if (!this.IsValid)
        {
            string msg = "";
            // Loop through all validation controls to see which
            // generated the errors.
            foreach (IValidator aValidator in this.Validators)
            {
                if (!aValidator.IsValid)
                {
                    msg += "<br />" + aValidator.ErrorMessage;
                }
            }
            Label1.Text = msg;
        }
    }
    

    You may be missing the step 4 on this msdn instruction for custom validator.

    step 4 -"Add a test in your ASP.NET Web page code to check for validity. For details, see How to: Test Validity Programmatically for ASP.NET Server Controls."