简体   繁体   中英

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?

Try two things:

this.SalaryPaidByEFT.SelectedItem.Text == "Yes"

or

args.Value == "Yes"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM