asp.net.ph

Skip Navigation Links

Validating Against Values in a Database

ASP.NET Web Forms   Web Forms Server Controls   Web Forms Validation


You can validate a user’s entry against a database to be sure that what the user has entered is a recognized value. To do this, you must write code in a CustomValidator control that loops through a table and looks for data matches.

To validate against a database

  1. Add a CustomValidator control to the page and set the following properties:

Property Setting
ControlToValidate The ID of the input control that the validation control will evaluate.
Display The display behavior for the specified validation control.
ErrorMessage The error message to display in the ValidationSummary control if validation fails.
Text The error message to display in the validation control when validation fails.
  1. Create an event handler for the CustomValidator control’s ServerValidate event. In the event handler, add code to look through the database and check the user’s input against the dataset.

NOTE: If the user leaves a control blank, the control passes the comparison validation. To force the user to enter a value, add a RequiredFieldValidator as well. For details, see Validating Required Entries.

  1. In your Web Forms code, check for validity. For details, see Testing Validity Programmatically.

The following example shows how you can validate a user’s entry by looking it up in a table. In this instance, the user has entered an e-mail address that is validated against e-mail addresses stored in a table. The custom validation logic loops through the rows in a table that is part of the dataset available to the page.

private void lookUpEntry ( object source,  ServerValidateEventArgs args ) {

   DataView dv;
   dv = myDataSet.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 [ "email_address" ].ToString ( );
      // Compare e-mail address against user’s entry
      if ( txtEmail == args.Value ) {
         args.IsValid = true;

      }
   }
}
  C# VB

See Also

Validating Against a Specific Value   Validating Against a Data Type   CompareValidator Control   CompareValidator Class   Data Entry Validation ( Client-Side )



© 2025 Reynald Nuñez and asp.net.ph. All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note