如果 javascript 验证失败,防止页面被回发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17781507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:36:47  来源:igfitidea点击:

Prevent page being post back if javascript validations fails

c#javascriptasp.netvalidation

提问by Saurabh Palatkar

I've following asp text box:

我有以下 asp文本框

<asp:TextBox ID="txtPasswrod" runat="server"></asp:TextBox>

below this text box I've error message label, which is initially hiddenuntil the js validationof the text box fails:

在此文本框下方我有错误消息标签,它最初隐藏的,直到文本框的js 验证失败

<label id="errorMsg" for="pwd" style="display:none">error</label >

Following is the jsfor textbox validation:

以下是用于文本框验证js

function validation() 
{
  var pwd = document.getElementById("txtPasswrod").value;
  if (pwd == null || pwd == "") 
  {
    document.getElementById("error").style.display = 'block';
    return false;
  }
}

Following is the asp button, whose OnClientClickevent I am calling validation()function:

以下是asp 按钮,我正在调用它的OnClientClick事件验证()函数:

<asp:Button ID="btnSubmit" runat="server" Text="Submit" 
     onclick="btnSubmit_Click" OnClientClick="validation()"/>

The validation is working all fine, but the problem is that when text boxis emptyand my validation failsthe jsshould prevent page from being post back, but the js allowing the page being post backand my validation jst becoming useless.

验证工作一切正常,但问题是当文本框并且我的验证失败时js应该阻止页面回发,但js 允许页面回发并且我的验证 jst 变得无用

Please tell me how to prevent page postback on failing the js validation.

请告诉我如何在 js 验证失败时防止页面回发

回答by ssilas777

Modify validation()to return validation(), This will stop page to post if functionreturns false.

修改validation()return validation(),如果function返回,这将停止页面发布false

<asp:Button ID="btnSubmit" runat="server" Text="Submit" 
     onclick="btnSubmit_Click" OnClientClick="return validation();"/>

回答by ssilas777

You need a slight change in your JS script. You need to add .ClientIDas the control you are specifying is a server control. Or if you are on .net 4.0 , you can use ClientIDMode= "Static"to access the control as you are using in your code.

您需要对 JS 脚本稍作更改。您需要添加,.ClientID因为您指定的控件是服务器控件。或者,如果您在 .net 4.0 上,则可以ClientIDMode= "Static"在代码中使用时访问控件。

function validation() {
                var pwd = document.getElementById('<%=txtPasswrod.ClientID').value;
                if (pwd == null || pwd == "") 
                {
                    document.getElementById("errorMsg").style.display = 'block';
                    return false;
                }
            }

Now call the validation method something like this:

现在像这样调用验证方法:

<asp:Button ID="btnSubmit" runat="server" Text="Submit" 
     onclick="btnSubmit_Click" OnClientClick="return validation();"/>