简体   繁体   English

验证失败时停止触发asp.net btnsave.click事件

[英]stop asp.net btnsave.click event from firing when validation fails

I have this java script validation function that fires when the client clicks btnsave if the text of the text box is empty then a message box is displayed and the focus is on the text box but i cannot seem to prevent the page from posting back when the validation fails AM I missing something. 我有此Java脚本验证功能,如果文本框的文本为空,则在客户端单击btnsave时将触发此消息,然后显示一个消息框,并且焦点位于文本框上,但我似乎无法阻止该页面在验证失败,我遗漏了一些东西。 here is my code 这是我的代码

function validate() 
  {
      var itemscanned;
      itemscanned = document.getElementById('txtItemCode');
      if (itemscanned.value == '') 
      {
          alert("Plz Enter Item Code");
          return false;
         itemscanned.focus
      }
      else 
      {
          alert(itemscanned.value);
      }
  }

像这样在函数名称前写返回

   <asp:Button ID="btnSave" runat="server" Text="Save" CssClass="buttons"  OnClientClick="return validate()"/>

If this is an ASP.NET WebForms application, you really should consider using the Validator controls . 如果这是ASP.NET WebForms应用程序,那么您确实应该考虑使用Validator控件 They handle all of client-side logic you are asking for. 它们处理您要求的所有客户端逻辑。

If you are using MVC, there is also a way to do model validation on the client side . 如果您使用的是MVC,则还有一种方法可以在客户端进行模型验证

add this if its asp.net button control 如果其asp.net按钮控件将其添加

OnClientClick = "return validate();"

if it is html button add this 如果是html按钮,请添加此

onclick = "return validate();"

Ît belongs how you handle the events. 它属于您处理事件的方式。 Please show the asp markup and the binding of the javascript event. 请显示asp标记和javascript事件的绑定。

You can try to stop event propagation using javascript: 您可以尝试使用javascript停止事件传播:

event.stopPropagation();

Read about it here: https://developer.mozilla.org/en-US/docs/DOM/event.stopPropagation 在此处阅读有关内容: https : //developer.mozilla.org/en-US/docs/DOM/event.stopPropagation

Note: you have to get the event as an parameter to the validate function: 注意:您必须将事件作为validate函数的参数获取:

function validate(event) {

    var itemscanned;    
    itemscanned = document.getElementById('txtItemCode');
    if (itemscanned.value == '') {
        alert("Plz Enter Item Code");
        event.stopPropagation();
        itemscanned.focus
        return false;
    }
    else
    {
        alert(itemscanned.value);
    }
}​

Hope this helps. 希望这可以帮助。 It's very important how you bind the validate function the button, because asp.net generates a lot of javascript on its own (google for asp.net client validation). 绑定按钮的validate函数非常重要,因为asp.net会自己生成很多JavaScript(用于asp.net客户端验证的Google)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM