2013-07-31 58 views
1

我正在學習如何使用自定義驗證器進行服務器端驗證,但似乎無法使其工作。每當我點擊按鈕,文本框爲空,錯誤信息就不會顯示出來。我究竟做錯了什麼?自定義驗證器不能用於文本框

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

<asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1" 
    OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="ValidateGp" 
    ErrorMessage="This is a custom error validator" runat="server"/> 

<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="ValidateGp"/> 

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args) 
{ 
    if (args.Value.Equals(string.Empty)) 
    { 
     args.IsValid = false; 
    } 
    else 
    { 
     args.IsValid = true; 
    } 
} 
+0

可能的重複:http://stackoverflow.com/questions/5119821/asp-net-custom-validator-not-firing-for-textbox – 2013-07-31 04:32:11

回答

3

你錯過了ValidateEmptyText =「真」爲

<asp:CustomValidator ID="CustomValidator1" 
        ValidateEmptyText="true" runat="server" ValidationGroup="ValidateGp" ErrorMessage="This is a custom error validator" ControlToValidate="TextBox1" OnServerValidate="CustomValidator1_ServerValidate"></asp:CustomValidator> 
0

或者以迫使空驗證,在某些情況下一個空的文本框是一個有效的(!),我建議你捕獲TextBox變化事件並在那裏強制Page.Validate()