2010-06-11 46 views
0

我有一個5行和2列的表。每個單元格都包含一個文本框。如果每列中的一個文本框爲空,我想顯示錯誤。我希望連續兩個文本框都被填充或者兩個都不填。javascript驗證:比較2個文本框的值

我怎樣才能通過Asp.net驗證控件來做到這一點?

我想擴展CompareValidator,以便它只會驗證,如果controlToValidate和controlToCompare都有一些文本或兩者都是空的。

+0

那麼,你想使用JavaScript驗證,或ASP.net驗證..他們不是很相同 – 2010-06-11 14:43:26

+0

我想使用客戶端驗證使用Asp.net驗證。 – coure2011 2010-06-11 16:26:17

回答

0

您將需要使用一個CustomValidator並處理其ServerValidate事件(並可選地,它的ClientValidationFunction客戶端驗證)。您可以在頁面上執行一個操作並檢查所有行,或者每行可以有一行,並使用ControlToValidate屬性爲您驗證的行提供上下文。

客戶端驗證的任何示例將取決於您的佈局和您正在使用的任何JavaScript框架。它可能是這個樣子:

<table> 
    <tr> 
     <td><asp:TextBox runat="server" ID="TextBox11" /></td> 
     <td><asp:TextBox runat="server" ID="TextBox12" /></td> 
    </tr> 
    <tr> 
     <td><asp:TextBox runat="server" ID="TextBox21" /></td> 
     <td><asp:TextBox runat="server" ID="TextBox22" /></td> 
    </tr> 
    <tr> 
     <td><asp:TextBox runat="server" ID="TextBox31" /></td> 
     <td><asp:TextBox runat="server" ID="TextBox32" /></td> 
    </tr> 
    <tr> 
     <td><asp:TextBox runat="server" ID="TextBox41" /></td> 
     <td><asp:TextBox runat="server" ID="TextBox42" /></td> 
    </tr> 
    <tr> 
     <td><asp:TextBox runat="server" ID="TextBox51" /></td> 
     <td><asp:TextBox runat="server" ID="TextBox52" /></td> 
    </tr> 
</table> 
<asp:CustomValidator ID="TextBoxPairValidator" runat="server" ControlToValidate="TextBox11" ClientValidationFunction="TextBoxPairValidator_ClientValidate" /> 

<script type="text/javascript"> 
    (function() { 
     window.TextBoxPairValidator_ClientValidate = function (sender, args) { 
      var other = document.getElementById(sender.id.slice(0, -1) + '2'); 
      args.IsValid = (sender.value === '' && other.value === '') 
          || (sender.value !== '' && other.value !== ''); 
     }; 
    }()); 
</script> 

這個例子明顯假設一個相當簡單的佈局,以及相對靜態的命名(例如,如果你的控件是在一個命名容器,你可能無法使用該ID招走從一個文本框到另一個文本框)。希望這足以讓你開始。

+0

任何代碼示例? – coure2011 2010-06-12 05:10:34