【问题标题】:stopping the server side execution with custom validator使用自定义验证器停止服务器端执行
【发布时间】:2020-07-15 03:03:49
【问题描述】:

我有一个带有最小年龄自定义验证器的表单。我在该表单上有提交按钮。当自定义验证器启动时,我不希望执行提交按钮内的代码,因此当不满足最低年龄要求并将 ServerValidateEventArgs 参数设置为 false 时。提交按钮内的代码被执行

下面是我的自定义验证器:

<asp:CustomValidator Display="None" ID="CustomValidator1" runat="server" OnServerValidate="ageValidator" ControlToValidate="txtDOB" ErrorMessage="CustomValidator"  />

下面是我的出生日期文本框:

<input   id="txtDOB" placeholder="mm/dd/yyyy" type="text" data-role="datebox" value="" runat="server"  ></input>

我在那个页面上也有提交按钮:

<asp:Button ID="btnSubmit" runat="server" Text="Submit" data-icon="check" OnClick="btnSubmit_Click" UseSubmitBehavior="true"   />

下面是我的自定义验证器代码:

protected void ageValidator(object source, ServerValidateEventArgs args)
{
    DateTime dtStart = DateTime.Parse(txtDOB.Value.ToString());
    TimeSpan sp = DateTime.Now - dtStart;

    if (sp.Days < 16 * 365)
    {
        args.IsValid = false;
        CustomValidator1.ErrorMessage = "You have to be at least 16 ";
        return ;
    }
    else
        args.IsValid = true;
}

protected void btnSubmit_Click(object sender, System.EventArgs e)
{
    // some code here
}

当我点击提交按钮时,自定义验证器代码会被执行,然后无论参数是真还是假,提交按钮中的代码都会被执行。如果 args 为 false,我不希望执行提交按钮中的代码,但这不会发生。

我们将不胜感激。

【问题讨论】:

    标签: c# asp.net customvalidator


    【解决方案1】:

    btnSubmit_Click 内部,您可以测试Page.IsValid(您的自定义验证器设置为false)并根据该答案决定是否执行其他任何操作。

    【讨论】:

      【解决方案2】:

      评论

      您可以通过属性 ErrorMessage = "You must be at least 16" 在 ASPX 本身中设置错误消息。方法中不需要return

      你必须在这样的方法中添加Page.IsValid

      if (Page.IsValid) 
           {
      
              SomeLabelMessage.Text = "Page is valid.";
      
           }
      
           else 
           {
      
              SomeLabelMessage.Text = "Page is not valid!";
      
           }
      

      【讨论】:

        猜你喜欢
        • 2012-07-31
        • 1970-01-01
        • 2018-07-23
        • 1970-01-01
        • 2017-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-20
        相关资源
        最近更新 更多