.NET CustomValidator:防止提交按钮

时间:2018-12-12 15:13:31

标签: c# asp.net .net webforms

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

这是我的标记。

<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为false,它仍然会继续触发Submit按钮。必填字段和常规字段验证器则不需要。如何获取CustomValidator来阻止按钮的OnClick触发或继续?

1 个答案:

答案 0 :(得分:1)

您还需要创建客户端验证。您可以使用验证器的ClientValidationFunction来完成此操作。

<asp:CustomValidator ID="CustomValidator1" runat="server" ControlToValidate="tbEmail"
   ClientValidationFunction="allowedDomains" ErrorMessage="Not Valid"></asp:CustomValidator>

<script type="text/javascript">
    function allowedDomains(sender, element) {
        var approvedDomains = ['<%= string.Join("', '", approvedEmailDomains) %>'];
        element.IsValid = $.inArray(element.Value, approvedDomains) > -1;
    }
</script>

要执行此操作,您需要一个public列表

public List<string> approvedEmailDomains;

protected void Page_Load(object sender, EventArgs e)
{
    approvedEmailDomains = new List<string>()
    {
        "domainnameihid.com",
        "stackoverflow.com"
    };
}