.NET CustomValidator:阻止提交按钮

我正在尝试将自定义字段验证器添加到一些遗留代码。如果电子邮件不属于某个域,它应该阻止表单触发。


这是我的标记。


<asp:Textbox id="tbEmail" autocomplete="off" CssClass="txt260" runat="server" TabIndex="1"></asp:Textbox>          

<asp:RequiredFieldValidator id="rfvEmail" runat="server" Display="Dynamic" ForeColor="" ControlToValidate="tbEmail" ErrorMessage="Required" CssClass="ValidatorError">Required</asp:RequiredFieldValidator>

<asp:CustomValidator id="cfvEmail" runat="server" Display="Dynamic" ControlToValidate="tbEmail" ErrorMessage="Invalid Email" CssClass="ValidatorError" OnServerValidate="tbEmail_CustomValidate"></asp:CustomValidator>

<asp:RegularExpressionValidator id="regExpEmail" runat="server" Display="Dynamic" ForeColor="" ControlToValidate="tbEmail" ErrorMessage="Invalid" CssClass="ValidatorError"></asp:RegularExpressionValidator>

...


<asp:Button ID="bSubmit" Text=" CREATE ACCOUNT " CssClass="NewButton" runat="server" OnClientClick="DisabledUpdateButton()" OnClick="bSubmit_Click" />

这是 C# 代码:


protected void tbEmail_CustomValidate(object source, ServerValidateEventArgs args)

{

    List<string> approvedEmailDomains = new List<string>()

    {

        "domainnameihid.com"

    };


    if (!approvedEmailDomains.Any(x => tbEmail.Text.EndsWith(x)))

    {

        args.IsValid = false;

    }

}

当我写一个无效的域名时,代码落入args.IsValid = false。一旦 args.IsValid 为假,它仍然会继续触发提交按钮。必需和常规字段验证器没有。如何获取 CustomValidator 以防止按钮的 OnClick 触发或继续?




凤凰求蛊
浏览 95回答 1
1回答

慕勒3428872

您还需要创建客户端验证。您可以使用ClientValidationFunctionValidator 来执行此操作。<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="tbEmail"&nbsp; &nbsp;ClientValidationFunction="allowedDomains" ErrorMessage="Not Valid"></asp:CustomValidator><script type="text/javascript">&nbsp; &nbsp; function allowedDomains(sender, element) {&nbsp; &nbsp; &nbsp; &nbsp; var approvedDomains = ['<%= string.Join("', '", approvedEmailDomains) %>'];&nbsp; &nbsp; &nbsp; &nbsp; element.IsValid = $.inArray(element.Value, approvedDomains) > -1;&nbsp; &nbsp; }</script>为此,您需要一个public列表public List<string> approvedEmailDomains;protected void Page_Load(object sender, EventArgs e){&nbsp; &nbsp; approvedEmailDomains = new List<string>()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; "domainnameihid.com",&nbsp; &nbsp; &nbsp; &nbsp; "stackoverflow.com"&nbsp; &nbsp; };}
打开App,查看更多内容
随时随地看视频慕课网APP