如果验证错误,请停止回发

时间:2012-08-13 09:29:57

标签: c# javascript jquery .net validation

我有以下文本框控件;

   <asp:TextBox ID="txtAmount" runat="server" AutoPostBack="true" Width="85px" class="validate[ERExpenseTypeDaterequired,custom[float]]"
                                OnTextChanged="txtAmount_TextChanged"   ></asp:TextBox>

此处,如果文本框中有任何值更改,则会调用txtAmount_TextChanged,因为控件中有AutoPostBack="true"

因此,如果我们在文本框中放置一个非数字值,验证错误将使用Jquery从属性Class中触发,但是从文本框中弹出一个红色框的错误将不会停留超过3秒,它会在该页面会在3秒内发回,此帖子正好发生,因为有AutopostBack="true"

我不能Autopostback="false"因为,我需要根据当场的文本框值更改进行一些计算。

如果我执行Autopostback="false",页面将不会回发并且错误消息永远保留,但我无法对“txtAmount_TextChanged”事件进行任何计算,因为如果{{Autopostback="false"事件永远不会在textchcange上调用此事件{1}}。

那么,如果此文本框中有任何验证错误,我该怎么做才能阻止此回发?

4 个答案:

答案 0 :(得分:2)

function txtAmount_TextChanged(){
    //do validations here, Eg: validate if txtAmount is valid amount and "> 0"
   return false; //if somethings's wrong, else true

}

答案 1 :(得分:1)

您需要添加一个客户端事件处理程序,并在您不希望发生PostBack时从它返回false。

<asp:TextBox onkeydown="return doMyCheck()" ID="txtAmount" runat="server"
  AutoPostBack="true" Width="85px" class="validate[ERExpenseTypeDaterequired,custom[float]]"
  OnTextChanged="txtAmount_TextChanged"></asp:TextBox>

JavaScript的:

function doMyCheck() {
  if (// call your jQuery validity check) 
    return false;
}

答案 2 :(得分:1)

使用Input事件使用jquery

检查文本框中添加的文本
jQuery('#txtAmount').live('input', function() 
   {
     // do your Validation 
     // If Valid return True
     // If Invalid Return False
   }
) 

答案 3 :(得分:1)

你可以使用jquery更改功能

$('#txtbox').change(function() { if(validationfail){return false;} );


你也可以使用keychange事件

 $('#txtbox').keyup(function() { 
       if(validationfail){return false;} 
    });