简体   繁体   中英

asp.net CustomValidator server-side does not stop my program?

I have a DropDownList bound to a DB. I also manually add to it an item "(other)"

When a user selects "(other)", JQuery fires and .Show() a hidden <asp:TextBox> where the user must input something.

I am attempting to validate this TextBox. Of course since I'm just hiding it using client-side, I can't use RequiredFieldValidator+RegularExpressionValidator so I tried a CustomValidator which I'm not very familiar with:

protected void validatorOther(object sender, ServerValidateEventArgs e)
{
    if (dropdownVisitorType.SelectedItem.ToString() == "(other)")
    {
        e.IsValid = (textboxOtherVisitorType.Text != "");
    }
}

protected void buttonRegister_Click(object sender, EventArgs e)
{
    //a whole bunch of code here...
}

And then from my aspx

<asp:CustomValidator runat="server" id="validatorOtherVisitorType" ValidateEmptyText="true" onservervalidate="validatorOther" errormessage="*" />

When I try to debug, it seems that e.IsValid will successfully return false . However, my webpage seems to just ignore it and proceed anyway, making the validator useless. What am I doing wrong?

You need to force validation on register button click:

this.Page.Validate();
if (this.Page.IsValid)
{
// your registration logic.
}

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