FormView控制項的幾種驗證方法

來源:互聯網
上載者:User

(一) 利用驗證伺服器控制項
進入Formview的模版編輯狀態,選擇InsertItemTemplate模版或EditItemTemplate模版,
將驗證伺服器控制項(如RequiredFieldValidator)拖放到開啟的相應模版,然後在CtrolToValidate屬性中指定需要驗證的 相應欄位,在ErrorMessage屬性中輸入出錯提示資訊即可。

(二) 利用FormView的ItemInserting和ItemUpdating事件
例如:

protected void FormView1_ItemInserting(object sender, FormViewInsertEventArgs e)
    {
        string useridstr=e.Values["userID"].ToString();
        TextBox userid = (TextBox)FormView1.FindControl("userid");
        if (useridstr.Length < 4 || useridstr.Length > 15)     //userID 是綁定的欄位
        {
            Page.RegisterStartupScript("錯誤", "<script>alert('管理員帳號在4-15位之內');</script>");
            userid.Focus();
            e.Cancel = true;
            return;  ////相當於 javascript: return false;
        }
        else
        {
            if (common.isValidUserid(useridstr) == false)
            {
                Page.RegisterStartupScript("錯誤", "<script>alert('使用者名稱由數字和字母組成,不能包含特殊字元,有字母開頭不能以數字開頭');</script>");
                userid.Focus();
                e.Cancel = true;
                return;
            }
               
        }

              }

 

(三) 利用與FormView綁定的SqlDataSource資料來源控制項的Inserting和Updating事件
例如:
第三種方法與第二類似

 

這三種方法中,本人認為利用SqlDataSource.Inserting方法(或SqlDataSource.Updating方法)最可取。 第一種方法很方便,但想做到出錯資訊集中處理就較難。第三種方法移植性較好,GridView控制項、DetailsView控制項均可使用。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.