Problem You need to make sure the data a user enters matches an entry in a database. Solution Add a CustomValidator to the .aspx file. Then add an event handler to the codebehind for the CustomValidator control's ServerValidate event, its purpose beingto validate the user entries against the database. In the .aspx file: Add a CustomValidator control that validates the entries against the database during server-side validation. Add a Login (or equivalently named) button. In the code-behind class for the page, use the .NET language of your choice to: Add an event handler for the CustomValidator control's ServerValidate event, its purpose beingto provide the server-side validation of the user's entries against the database. Add code to the event handler for the Login button's click event to check the Page.IsValid property and verify that all validation was successful (see Recipe 3.1 for details). Figure 3-12 shows a typical form with normal output prior to data entry. Figure 3-13 shows the form with a validation error message. Examples 3-10, 3-11 through 3-12 show the .aspx and code-behind files for our application that implements the solution. Discussion One of the most common examples of this recipe's handiness is when implementing a classic login page. The approach we favor in this scenario uses a CustomValidator to perform the user authentication and a ValidationSummary to display error information. Figure 3-12. Form with database validation outputnormal Figure 3-13. Form with database validation outputwith error message In our example, RequiredFieldValidator controls are used for the login ID and password fields. (RequiredFieldValidator controls are described in Recipe 3.1.) The user must supply both to gain access to her account. Unlike the other recipes in this chapter, our approach for this recipe has the CustomValidator control's EnableClientScript attribute set to False to disable client side validation because the database validation can be done only on the server side: <asp:CustomValidator Runat="server" Display="None" EnableClientScript="False" ErrorMessage="Login ID or Password Is Invalid" OnServerValidate="cvAuthentication_ServerValidate" /> The ValidationSummary is set up to display all validation errors. This includes errors from the RequiredFieldValidator controls and the CustomValidator used for user authentication. The ServerValidate event for the CustomValidator (cvAuthentication_ServerValidate) is used to perform the user authentication by checkingif a user exists in the database with the entered login ID and password, as shown in Examples 3-11 (VB) and 3-12 (C#). If the user is found in the database, the args.IsValid property is set true to indicate the validation was successful. Otherwise, it is set False to indicate the validation failed. The event handler for the Login button's click event (btnLogin_Click) then checks to see if the page is valid before proceeding with actions required to log the user into the system. As you may have noticed, the approach used in this recipe is an amalgam of all the approaches used in the chapter's other recipes. Having used this approach to control essentially all the aspects of validation, you can adapt it to perform almost any validation your application requires. See Also Recipes 3.1 and 3.5 Example 3-10. Form with database validation (.aspx) <%@ Page Language="VB" MasterPageFile="~/ASPNetCookbookVB.master" AutoEventWireup="false" CodeFile="CH03CustomDatabaseValidationVB.aspx.vb" Inherits="ASPNetCookbook.VBExamples.CH03CustomDatabaseValidationVB" title="Custom Database Validation" %> <asp:Content Runat="server" ContentPlaceHolder> <div align="center" > Custom Selection Validation (VB) </div> <table align="center" > </tr> <td colspan="2" align="left"> <asp:ValidationSummary Runat="server" Css DisplayMode="BulletList" EnableClientScript="True" HeaderText="Error Summary" /> <asp:CustomValidator Runat="server" Display="None" EnableClientScript="False" ErrorMessage="Login ID or Password Is Invalid" OnServerValidate="cvAuthentication_ServerValidate" /> </td> </tr> </tr> <td >Login ID: </td> <td> <asp:TextBox Runat="server" Columns="30" Css /> <asp:RequiredFieldValidator Runat="server" ControlToValidate="txtLoginID" Css Display="Dynamic" EnableClientScript="True" ErrorMessage="Login ID Is Required"> <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> </asp:RequiredFieldValidator> </td> </tr> </tr> <td >Password: </td> <td> <asp:TextBox Runat="server" TextMode="Password" Columns="30" Css /> <asp:RequiredFieldValidator Runat="server" ControlToValidate="txtPassword" Css Display="Dynamic" EnableClientScript="True" ErrorMessage="Password Is Required"> <img src="/books/1/505/1/html/2/images/arrow_alert.gif" alt="arrow"/> </asp:RequiredFieldValidator> </td> </tr> </tr> <td colspan="2" align="center"> <br/> <input runat="server" type="button" value="Login" causesvalidation="true" onserverclick="btnLogin_Click"/> </td> </tr> </table> </asp:Content> | Example 3-11. Form with database validation code-behind (.vb) Option Explicit On Option Strict On Imports System.Configuration.ConfigurationManager Imports System.Data Imports System.Data.OleDb Namespace ASPNetCookbook.VBExamples ''' <summary> ''' This class provides the code behind for ''' CH03CustomDatabaseValidationVB.aspx ''' </summary> Partial Class CH03CustomDatabaseValidationVB Inherits System.Web.UI.Page '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the authentication server ''' validate event. It is responsible for checking the login ID and ''' password in the database to authenticate the user. ''' </summary> ''' ''' <param name="source">Set to the sender of the event</param> ''' <param name="args">Set to the event arguments</param> Protected Sub cvAuthentication_ServerValidate(ByVal source As Object, _ ByVal args As ServerValidateEventArgs) Dim dbConn As OleDbConnection = Nothing Dim dCmd As OleDbCommand = Nothing Dim strConnection As String Dim strSQL As String Try 'initially assume credentials are invalid args.IsValid = False 'get the connection string from web.config and open a connection 'to the database strConnection = _ ConnectionStrings("dbConnectionString").ConnectionString dbConn = New OleDb.OleDbConnection(strConnection) dbConn.Open( ) 'build the query string and check to see if a user with the entered 'credentials exists in the database strSQL = "SELECT AppUserID FROM AppUser " & _ "WHERE LoginID=? AND " & _ "Password=?" dCmd = New OleDbCommand(strSQL, dbConn) dCmd.Parameters.Add(New OleDbParameter("LoginID", _ txtLoginID.Text)) dCmd.Parameters.Add(New OleDbParameter("Password", _ txtPassword.Text)) 'check to see if the user was found If (Not IsNothing(dCmd.ExecuteScalar( ))) Then args.IsValid = True End If Finally 'cleanup If (Not IsNothing(dbConn)) Then dbConn.Close( ) End If End Try End Sub 'cvAuthentication_ServerValidate '''*********************************************************************** ''' <summary> ''' This routine provides the event handler for the login button click ''' event. It is responsible for processing the form data. ''' </summary> ''' ''' <param name="sender">Set to the sender of the event</param> ''' <param name="e">Set to the event arguments</param> Protected Sub btnLogin_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) If (Page.IsValid) Then 'user has been authenticated so proceed with allowing access 'to the site End If End Sub 'btnLogin_Click End Class 'CH03CustomDatabaseValidationVB End Namespace | Example 3-12. Form with database validation code-behind (.cs) using System; using System.Configuration; using System.Data; using System.Data.OleDb; namespace ASPNetCookbook.CSExamples { /// <summary> /// This class provides the code behind for /// CH03CustomDatabaseValidationCS.aspx /// </summary> public partial class CH03CustomDatabaseValidationCS : System.Web.UI.Page { ///*********************************************************************** /// <summary> /// This routine provides the event handler for the authentication server /// validate event. It is responsible checking the login ID and password /// in the database to authenticate the user. /// </summary> /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void cvAuthentication_ServerValidate(Object source, System.Web.UI.WebControls.ServerValidateEventArgs args) { OleDbConnection dbConn = null; OleDbCommand dCmd = null; String strConnection = null; String strSQL = null; try { // initially assume credentials are invalid args.IsValid = false; // get the connection string from web.config and open a connection // to the database strConnection = ConfigurationManager. ConnectionStrings["dbConnectionString"].ConnectionString; dbConn = new OleDbConnection(strConnection); dbConn.Open( ); // build the query string and check to see if a user with the // entered credentials exists in the database strSQL = "SELECT AppUserID FROM AppUser " + "WHERE LoginID=? AND " + "Password=?"; dCmd = new OleDbCommand(strSQL, dbConn); dCmd.Parameters.Add(new OleDbParameter("LoginID", txtLoginID.Text)); dCmd.Parameters.Add(new OleDbParameter("Password", txtPassword.Text)); // check to see if the user was found if (dCmd.ExecuteScalar( ) != null) { args.IsValid = true; } } // try finally { // cleanup if (dbConn != null) { dbConn.Close( ); } } // finally } // cvAuthentication_ServerValidate ///*********************************************************************** /// <summary> /// This routine provides the event handler for the login button click /// event. It is responsible for processing the form data. /// </summary> /// <param name="sender">Set to the sender of the event</param> /// <param name="e">Set to the event arguments</param> protected void btnLogin_Click(Object sender, System.EventArgs e) { if (Page.IsValid) { // user has been authenticated so proceed with allowing access // to the site } } //btnLogin_Click } // CH03CustomDatabaseValidationCS } | |