为了账号安全,请及时绑定邮箱和手机立即绑定

.NET CustomValidator:阻止提交按钮

.NET CustomValidator:阻止提交按钮

C#
凤凰求蛊 2022-06-12 10:31:31
我正在尝试将自定义字段验证器添加到一些遗留代码。如果电子邮件不属于某个域,它应该阻止表单触发。这是我的标记。<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 触发或继续?
查看完整描述

1 回答

?
慕勒3428872

TA贡献1848条经验 获得超6个赞

您还需要创建客户端验证。您可以使用ClientValidationFunctionValidator 来执行此操作。


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

    };

}


查看完整回答
反对 回复 2022-06-12
  • 1 回答
  • 0 关注
  • 94 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信