Export (0) Print
Expand All

AJAX Validation

Retired Content

This content is outdated and is no longer being maintained. It is provided as a courtesy for individuals who are still using these technologies.
This page may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist.

Ff709918.note(en-us,PandP.10).gifNote:
This topic is duplicated in the documentation so that you can read all the pertinent information within a single section.

The AJAX Validation QuickStart combines ASP.NET AJAX technologies with the Enterprise Library Validation Application Block and ASP.NET validation controls to provide input validation within a responsive user interface.

Ff709918.note(en-us,PandP.10).gifNote:
The AJAX Validation QuickStart demonstrates how to implement several types of validation, and it is not designed to provide optimal performance over the network. For guidance on how to choose between different validation types, see the sections “Choosing the Validation Type”, “Selecting Validations Controls”, and “Validation Security Guidelines” in Validation Guidelines.

Business Scenario

The QuickStart uses a single page that contains an input form for a user profile. User profile information must follow certain rules that are validated in the page. The following table describes the fields that users have to fill in and their corresponding validation rules.

Field

Validation rules

Account Number

Must be validated against a list of valid account numbers that is maintained on the server.

E-mail

Must be a valid e-mail address format that is validated against a client-side regular expression (regex).

Name

Must contain up to 25 characters.

Age

Must be empty or between 16 years and 30 years.

Homepage

Must be a valid URL, and the page must exist and be reachable.

State

Must be validated against a list of valid 2-character U.S. states.

ZIP Code

Must be validated against a list of valid U.S. ZIP codes.

Apart from the per-field validation rules described in the preceding table, the selected ZIP code must be valid for the selected state.

Building and Running the QuickStart

The QuickStart ships as source code, which means you must compile it before running it. This QuickStart requires the following:

The AutoCompleteQuickStart project must include a reference to the ASP.NET AJAX Control Toolkit assembly. The following procedure describes how to build and run the QuickStart.

To build and run the QuickStart

  1. Download and extract the source code.
  2. Copy the AJAX Control Toolkit assembly (AJAXControlToolkit.dll) to the Lib\AjaxControlToolkit folder.
  3. Open the solution file Validation.sln.
  4. On the Build menu, click Rebuild Solution.
  5. Press F5 to run the QuickStart.

Implementation Notes

The following sections contain information that describes how the QuickStart uses validation.

Validation in the Profile Class

The solution contains a business entity named Profile that represents a user profile (the class is located in ValidationQuickStart\BusinessEntities\Profile.cs). The Profile class has Validation Application Block attributes specified on its properties. Some of the attributes are built-in Validation Application Block attributes, and some of the attributes are custom attributes. Custom attributes indicate that a custom validator must be used.

Properties Zip, State, and AccountNumber use custom validators. As an example, the following code shows the AccountNumber property with the [AccountNumberValidator] attribute applied. This attribute indicates that the custom AccountNumberValidator class is used to validate the AccountNumber property.

[AccountNumberValidator(MessageTemplateResourceType = typeof(Resources), MessageTemplateResourceName = "InvalidAccountNumberTemplateMessage")]
public string AccountNumber
{
     get { return _accountNumber; }
     set { _accountNumber = value; }
}

The AccountNumberValidator class, located in the file ValidationQuickStart\Validators\AccountNumberValidator.cs is a custom domain validator that restricts the account number to a predefined set of numbers.

public class AccountNumberValidator : DomainValidator<string>
{
    private static List<string> possibleAccounts = new List<string>(new string[] { "00001", "00002", "00003", "00004", "00005", "00006", "00007", "00008", "00009" });
     
    public AccountNumberValidator()
        : base(possibleAccounts)
    {
    }
}

The ZipCodeValidator class is a custom validator that verifies that a ZIP code is a valid U.S. ZIP code. Similarly, the StateValidator class is a custom validator that verifies that the state of a profile is a valid U.S. state. Both validators use the PostalInfoLookupDataSet dataset to perform the verification. This dataset contains the valid ZIP codes, cities, and states of the U.S. You can see the validators implementation inside the folder ValidationQuickStart\Validators.

Properties Email, Name, Age and Homepage use Validation Application Block built-in validators. As an example, the code for the Email property is shown in the following code. This property uses a RegexValidator to validate the property value against a regular expression that corresponds to an e-mail address.

[RegexValidator(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")]
public string Email
{
     get { return _email; }
     set { _email = value; }
}

For more information about built-in Validation Application Block validators, see Validation Application Block on MSDN.

Profile Information Page

The profile information page (located in ValidationQuickStart\Default.aspx) contains an input form for a user profile. To validate the input, it uses the following components:

  • VAB PropertyProxyValidator controls
  • ServerSideValidationExtender custom extender controls
  • ASP.NET built-in validators, such as the RegularExpressionValidator, the RequiredFieldValidator, and the CustomValidator

PropertyProxyValidator controls validate the user input using the validation rules defined with the Validation Application Block. The PropertyProxyValidator control does not support client-side validation; it performs only server-side validation. This means that you have to perform a postback to execute the validation logic. The Web Client Software Factory includes a custom extender control named ServerSideValidationExtender that enables any validator to be invoked with an asynchronous callback without performing a full postback, thus improving the UI responsiveness. The fields Account Number, Name, Age, State, and Zip use a PropertyProxyValidator control together with a ServerSideValidationExtender extender. The following markup code shows the Account Number text box together with the PropertyProxyValidator control applied to it and the ServerSideValidationExtender control.

<asp:TextBox
  ID="AccountNumberTextBox"
  runat="server"
  Width="320px"
  MaxLength="50">
</asp:TextBox>
<cc1:PropertyProxyValidator
  ID="AccountNumberPropertyProxyValidator"
  runat="server"
  ControlToValidate="AccountNumberTextBox"
  Display="Dynamic"
  PropertyName="AccountNumber"
  SourceTypeName="ValidationQuickStart.BusinessEntities.Profile">
</cc1:PropertyProxyValidator>
<ajaxtoolkitwcsfextensions:ServerSideValidationExtender
  ID="AccountNumberServerSideValidationExtender"
  runat="server"
  TargetControlID="AccountNumberPropertyProxyValidator">
</ajaxtoolkitwcsfextensions:ServerSideValidationExtender>

ASP.NET built-in validators provide both server-side and client-side validation (using JavaScript code). The benefit of using client-side validation is that it does not require a postback or a callback, thus it is faster than server-side validation and reduces the connection bandwidth usage. The fields Email, Name, Homepage, State, and Zip use built-in ASP.NET validators. The following code shows the code for the Email text box and the corresponding RegularExpressionValidator validator, which validates that the input is a valid e-mail address.

<asp:TextBox
  ID="EmailTextBox"
  runat="server" 
  Width="320px">
</asp:TextBox>
<asp:RegularExpressionValidator
  ID="EmailRegularExpressionValidator"
  runat="server"
  ControlToValidate="EmailTextBox"
  Display="Dynamic"
  ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
  * Invalid e-mail address.
</asp:RegularExpressionValidator>

The Profile Information page also includes two ASP.NET CustomValidator controls. One control is applied to the Homepage text box, and the other one does not apply to any control in particular; instead, it performs a cross-field validation between the State and the ZIP Code fields.

The HompageCustomValidator control, which applies to the Homepage text box, verifies that the URL entered exists and can be reached through an HTTP request. You can see the custom validation code in the code behind file of the Default.cs page.

protected void HompageCustomValidator_ServerValidate(object source, ServerValidateEventArgs args)
{
    string url = args.Value;
    Uri uri;
    if (Uri.TryCreate(url, UriKind.Absolute, out uri))
    {
        args.IsValid = UriExists(uri);
    }
    else
    {
        args.IsValid = false;
    }
}

private bool UriExists(Uri uri)
{
    try
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
        request.MaximumAutomaticRedirections = 4;
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        response.Close();
        return response.StatusCode == HttpStatusCode.OK;
    }
    catch
    {
        return false;
    }
}
Ff709918.note(en-us,PandP.10).gifNote:
Note: The implementation of the HomepageCustomValidator was introduced in the QuickStart as an example of a server-side validation. This implementation is intentionally simplistic and has scalability and performance concerns; therefore, it is not recommended for real-world applications.

To perform the cross-field validation between the State and the Zip Code fields, the AddressCustomValidator control uses the Validation Application Block self validation. Self-validation allows you to implement validation logic within the class you want to validate.

Ff709918.note(en-us,PandP.10).gifNote:
Note: For more information about self validation, see Using Self Validation.

The following code shows the self-validation method within the Profile class, which uses the PostalInfoLookupDataSet dataset to verify that the ZIP code entered belongs to the chosen state.

[SelfValidation]
public void ValidateAddress(ValidationResults results)
{
    if (!PostalInfoLookupDataSet.Instance.ZipBelongsToState(_zip, _state))
    {
        string errorMessage = string.Format(CultureInfo.CurrentCulture, Resources.InvalidAddressTemplateMessage, _zip, _state);
        ValidationResult result = new ValidationResult(errorMessage, this, "Zip", "Address", null);
        results.AddResult(result);
    }
}
Show:
© 2014 Microsoft