2015-04-02 44 views
0

我需要驗證人員的年齡,並且該字段應該是強制填寫的。此外,範圍應該是2-3位。一個驗證單獨工作,但數據也得到存儲,我不想。如何在c#中添加asp.net中的多個驗證碼

<asp:TextBox ID="txtAge" value="number" runat ="server" OnTextChanged="TextBox1_TextChanged"></asp:TextBox> 
<asp:RangeValidator ID="RangeValidator2" 
ControlToValidate="txtAge" 
MinimumValue="18" 
MaximumValue="80" 
Type="INTEGER" 
EnableClientScript="false" 
Text="The date must be between 18 and 80!" 
runat="server" /> 

請幫我解決這個問題。

+0

顯示你已經嘗試過的情況。 – 2015-04-02 13:44:28

+0

那麼問題是什麼?使用兩個驗證器。 RequiredFieldValidator和RangeValidator。 – 2015-04-02 13:48:19

+0

沒有它不適合我。而且不正確的數據也被存儲在數據庫中。 – zombie 2015-04-02 13:49:34

回答

0

例如:

<asp:RangeValidator ID="RangeValidatorAge" runat="server" 
ErrorMessage="Age must be between 1 & 100" 
MinimumValue="1" MaximumValue="100" 
ControlToValidate="txtAge" Type="Integer" 
ForeColor="Red" Display="Dynamic"> 
</asp:RangeValidator> 
<asp:RequiredFieldValidator ID="RequiredFieldValidatorAge" 
runat="server" ErrorMessage="Age is required" 
ControlToValidate="txtAge" ForeColor="Red" 
Display="Dynamic" > 
</asp:RequiredFieldValidator> 
+0

HEy Ayoub它不適合我工作。我需要一些代碼或組驗證類型的事情,因爲使用兩個以上的驗證是給我錯誤。 – zombie 2015-04-02 13:52:45

0

所以要禁用客戶端驗證,因此你已經使用EnableClientScript="false"。好吧,但你必須通過Page.Validate()來強制服務器端驗證:

protected void TextBox1_TextChanged(object sender, EventArgs e) 
{ 
    Page.Validate(); 
    if (Page.IsValid) 
    { 
     // save your data 
    } 
} 
+0

thanx指導蒂姆。 – zombie 2015-04-02 14:06:15

0

使用ValidationGroup

<asp:TextBox ID="txtAge" value="number" runat ="server" OnTextChanged="TextBox1_TextChanged" ValidationGroup="ag"></asp:TextBox> 
<asp:RangeValidator ID="RangeValidator2" 
ControlToValidate="txtAge" 
MinimumValue="18" 
MaximumValue="80" 
Type="INTEGER" 
EnableClientScript="false" 
Text="The date must be between 18 and 80!" 
runat="server" ValidationGroup="ag" /> 

<asp:RequiredFieldValidator ID="RequiredFieldValidatorAge" 
runat="server" ErrorMessage="Age is required" 
ControlToValidate="txtAge" ForeColor="Red" 
Display="Dynamic" ValidationGroup="ag"> 
</asp:RequiredFieldValidator> 
相關問題