無重新整理方式校正資料庫內容的驗證控制項

來源:互聯網
上載者:User
DOTNET裡的驗證架構確實很方便,對於一些表單的填寫的基本驗證,比如必填驗證,正則驗證等都能很好的處理,外還保證了伺服器端的驗證,真所謂省事又省心。也有些情況下需要驗證些比較複雜的邏輯,比如選了某個選項,就必須填寫某個文字框的內容,這種情況下,DOTNET也提供了擴充,有個Customvalidator可以解決。而對於某些內容需要到資料庫裡驗證下的,顯然光靠用戶端是不能實現的,用Cusomvalidator的伺服器端驗證確實可以實現,但是需要來回重新整理那麼一遍,當然有些煩人。因此弄了個自訂的驗證控制項,簡單擺弄了一下,整出了個DataBaseContentValidator。主要技術還是利用ICallbackEventHandler實現無重新整理操作,只不過這次還繼承了個BaseValidator。最終用起來跟一般的驗證控制項沒什麼差別,也是由於繼承了BaseValidator的原因。

具體請看
DataBaseContentValidator

用法:實現ValidateContent事件,然後設定事件參數的IsValid屬性aspx
1<asp:TextBox ID="dafd" runat="server"></asp:TextBox>
2            <cc1:DataBaseContentValidator runat="server" ID="dataBaseContentValidator1" Display="Dynamic"
3                ErrorMessage="不存在該供應商" OnValidateContent="dataBaseContentValidator1_ValidateContent"
4                SetFocusOnError="True" ControlToValidate="dafd" EnableClientScript="False"></cc1:DataBaseContentValidator>
5            <asp:Button ID="btn" runat="server" Text="check" OnClick="btn_Click1" />

CSharp
 1/**//// <summary>
 2        ///  ValidateContent事件
 3        /// </summary>
 4        /// <param name="sender"></param>
 5        /// <param name="e"></param>
 6        protected void dataBaseContentValidator1_ValidateContent(object sender, Shenba.CustomControl.DataBaseContentValidator.ValidateArgs e)
 7        {
 8            int recCount = 0;
 9            using (SqlConnection con = new SqlConnection(conString))
10            {
11                SqlCommand command = new SqlCommand("select count('a') from suppliers1 where CompanyName = @name", con);
12                command.Parameters.Add(new SqlParameter("@name", e.Value));
13                con.Open();
14                recCount = (int)command.ExecuteScalar();
15            }
16
17            // 根據結果設定參數的IsValid屬性
18            e.IsValid = recCount > Decimal.Zero;
19        }
20
21        protected void btn_Click1(object sender, EventArgs e)
22        {
23            if (Page.IsValid)
24            {
25                if (!Page.ClientScript.IsStartupScriptRegistered("Pass"))
26                {
27                    Page.ClientScript.RegisterStartupScript(GetType(), "Pass", "alert('Pass');", true);
28                }
29            }
30        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.