2009-09-11 36 views
6

我在我的網站上有以下內容。如何從下拉列表中選擇「其他」選項時驗證所需的文本?

來源[DropDownList中]

網站

搜索引擎

其他

其它來源[文本框]

我想使用ASP.Net驗證(我認爲比較驗證),所以t當在下拉列表中選擇「其他」並且沒有輸入文本時,觸發驗證並且無法提交頁面。

這可能嗎?

我試圖設置下拉到string.empty中的「其他」選項的值,並將其與一個空的文本框進行比較,但這不起作用。

我繼承的整個事情是在一個嚮導控件中,否則我會掛接一些客戶端腳本來自己觸發驗證。我不認爲我可以通過嚮導控制來做到這一點?

在此先感謝。

回答

9

在ASP.NET中沒有提供的檢驗器允許您執行基於另一個控制條件的驗證。但是,您可以通過使用在客戶端,服務器端或兩者上執行驗證的CustomValidator來實現此目的(建議至少進行服務器端驗證)。驗證器與嚮導一起運行良好。

ASP.NET標記示例:

<asp:DropDownList ID="OptionsDropDownList" runat="server"> 
     <asp:ListItem Text="Website" /> 
     <asp:ListItem Text="Search Engine" /> 
     <asp:ListItem Text="Other" /> 
    </asp:DropDownList> 
    <asp:TextBox ID="OtherTextBox" runat="server" /> 
    <asp:CustomValidator ID="custvOptionsDropDownList" runat="server" ControlToValidate="OptionsDropDownList" 
     ValidateEmptyText="true" Display="Dynamic" ClientValidationFunction="validateOtherTextBox" 
     ErrorMessage="This field is required!" OnServerValidate="ValidateOtherTextBox" /> 

的JavaScript ClientValidationFunction:

<script type="text/javascript" language="javascript"> 
    function validateOtherTextBox(event, args) { 
     var textbox = document.getElementById('<%= OtherTextBox.ClientID %>').value; 
     if (args.Value == 'Other') 
      args.IsValid = (textbox != ''); 
     else 
      args.IsValid = true; 
    } 
</script> 

代碼隱藏OnServerValidate:

protected void ValidateOtherTextBox(object source, ServerValidateEventArgs args) 
    { 
     if (OptionsDropDownList.SelectedValue == "Other") 
     { 
      args.IsValid = (OtherTextBox.Text.Trim() != ""); 
     } 
    } 

請注意,您可以選擇實施任何您需要的。您可以完全跳過Javascript驗證並刪除該代碼和ClientValidationFunction屬性。另外請注意,JavaScript通過使用ClientID屬性引用目標控件。這是必需的,因爲ASP.NET在輸出頁面時分配了不同的ID,並且您希望以這種方式將它提供給Javascript方法(查看頁面上的源代碼,您將看到控件名稱有一個額外的前綴等)。

0

你再查誰選項,選擇下拉列表中這樣

if (ddl.selecteditemindex == 1){ 
if (txtvalue.text == "") 
{ 
alert('you write something if selected other otherwise choose from a list'); 
} 
} 
相關問題