HOW TO:比對資料庫值驗證 ASP.NET 伺服器控制項

更新:2007 年 11 月

您可以比對資料庫驗證使用者的輸入,以確定使用者所輸入的值是可識別的值。若要這麼做,您必須在 CustomValidator 控制項中撰寫程式碼,這個控制項會尋找資料庫中的資料符合項目。

若要比對資料庫驗證

  1. CustomValidator 控制項加入至網頁,並設定下列屬性:

    屬性

    說明

    ControlToValidate

    要驗證控制項的 ID。

    ErrorMessage, Text, Display

    指定驗證失敗時顯示一或多個錯誤的文字和位置的屬性。如需詳細資訊,請參閱 HOW TO:控制 ASP.NET 伺服器控制項的驗證錯誤訊息顯示

  2. CustomValidator 控制項的 ServerValidate 事件建立事件處理常式。在該事件處理常式中,加入程式碼,以搜尋資料庫,並比對資料集檢查使用者的輸入。

    注意事項:

    如果使用者讓控制項保持空白,控制項會通過比較驗證。若要強制使用者輸入值,請同時加上 RequiredFieldValidator 控制項。如需詳細資訊,請參閱 HOW TO︰驗證 ASP.NET 伺服器控制項的必要項目

  3. 在 ASP.NET Web 網頁程式碼中加入一個檢查有效性的測試。如需詳細資訊,請參閱 HOW TO:以程式的方式測試 ASP.NET 伺服器控制項的有效性

    下列程式碼範例會顯示如何在資料庫資料表中查詢使用者的輸入以進行驗證。在這個例子中,使用者輸入了電子郵件地址,該電子郵件地址為要比對儲存在資料表中的電子郵件地址驗證。自訂的驗證邏輯會尋找網頁中可用的資料集中的資料表的資料列。

    Private Sub CustomValidator1_ServerValidate(ByVal _
       source As System.Object, ByVal args As _
       System.Web.UI.WebControls.ServerValidateEventArgs) _
       Handles CustomValidator1.ServerValidate
    
        Dim dv As DataView
        Dim dataset11 As New Data.DataSet
    
        dv = dataset11.Tables(0).DefaultView
    
        Dim datarow As DataRowView
        Dim txtEmail As String
        args.IsValid = False    ' Assume False
        ' Loop through table and compare each record against user's entry
        For Each datarow In dv
            ' Extract e-mail address from the current row
            txtEmail = datarow.Item("Alias").ToString()
            ' Compare e-mail address against user's entry
            If txtEmail = args.Value Then
                args.IsValid = True
                Exit For
            End If
        Next
    End Sub
    
    private void CustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
    {
        DataView dv;
        DataSet dataSet11 = new DataSet();
    
        dv = dataSet11.Tables[0].DefaultView;
        string txtEmail;
        args.IsValid = false;    // Assume False
        // Loop through table and compare each record against user's entry
        foreach (DataRowView datarow in dv)
        {
            // Extract e-mail address from the current row
            txtEmail = datarow["Alias "].ToString();
            // Compare e-mail address against user's entry
            if (txtEmail == args.Value)
            {
                args.IsValid = true;
            }
        }
    }
    

請參閱

概念

ASP.NET 伺服器控制項的驗證類型

其他資源

驗證 ASP.NET 控制項