2012-01-26 22 views
1

我有一個綁定到數據庫的DropDownList。我也手動添加一個項目「(other)」asp.net CustomValidator服務器端不會停止我的程序?

當用戶選擇「(other)」時,JQuery觸發並且.Show()隱藏<asp:TextBox>用戶必須在其中輸入內容。

我正在嘗試驗證此TextBox。當然,因爲我使用的客戶端只是隱藏它,我不能使用的RequiredFieldValidator +的RegularExpressionValidator所以我嘗試了其中的CustomValidator我不是很熟悉:

protected void validatorOther(object sender, ServerValidateEventArgs e) 
{ 
    if (dropdownVisitorType.SelectedItem.ToString() == "(other)") 
    { 
     e.IsValid = (textboxOtherVisitorType.Text != ""); 
    } 
} 

protected void buttonRegister_Click(object sender, EventArgs e) 
{ 
    //a whole bunch of code here... 
} 

然後從我的aspx

<asp:CustomValidator runat="server" id="validatorOtherVisitorType" ValidateEmptyText="true" onservervalidate="validatorOther" errormessage="*" /> 

當我嘗試調試時,看起來e.IsValid將成功返回false。然而,我的網頁似乎只是忽略它,並繼續進行,使驗證器無用。我究竟做錯了什麼?

回答

3

您需要強制的註冊按鈕點擊確認:

this.Page.Validate(); 
if (this.Page.IsValid) 
{ 
// your registration logic. 
} 
+0

這正是我需要的。非常感謝! – Baxter