CustomValidator ajax,AJAX Validation

AJAX Validation

10/20/2011

6 minutes to read

In this article

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.

Note

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.

Note

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:

Microsoft .NET Framework 3.5

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

Download and extract the source code.

Copy the AJAX Control Toolkit assembly (AJAXControlToolkit.dll) to the Lib\AjaxControlToolkit folder.

Open the solution file Validation.sln.

On the Build menu, click Rebuild Solution.

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

{

private static List possibleAccounts = new List(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.

ID="AccountNumberTextBox"

Width="320px"

MaxLength="50">

ID="AccountNumberPropertyProxyValidator"

ControlToValidate="AccountNumberTextBox"

Display="Dynamic"

PropertyName="AccountNumber"

SourceTypeName="ValidationQuickStart.BusinessEntities.Profile">

ID="AccountNumberServerSideValidationExtender"

TargetControlID="AccountNumberPropertyProxyValidator">

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.

ID="EmailTextBox"

Width="320px">

ID="EmailRegularExpressionValidator"

ControlToValidate="EmailTextBox"

Display="Dynamic"

ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">

* Invalid e-mail address.

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;

}

}

Note

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.

Note

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);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
资源包主要包含以下内容: ASP项目源码:每个资源包中都包含完整的ASP项目源码,这些源码采用了经典的ASP技术开发,结构清晰、注释详细,帮助用户轻松理解整个项目的逻辑和实现方式。通过这些源码,用户可以学习到ASP的基本语法、服务器端脚本编写方法、数据库操作、用户权限管理等关键技术。 数据库设计文件:为了方便用户更好地理解系统的后台逻辑,每个项目中都附带了完整的数据库设计文件。这些文件通常包括数据库结构图、数据表设计文档,以及示例数据SQL脚本。用户可以通过这些文件快速搭建项目所需的数据库环境,并了解各个数据表之间的关系和作用。 详细的开发文档:每个资源包都附有详细的开发文档,文档内容包括项目背景介绍、功能模块说明、系统流程图、用户界面设计以及关键代码解析等。这些文档为用户提供了深入的学习材料,使得即便是从零开始的开发者也能逐步掌握项目开发的全过程。 项目演示与使用指南:为帮助用户更好地理解和使用这些ASP项目,每个资源包中都包含项目的演示文件和使用指南。演示文件通常以视频或图文形式展示项目的主要功能和操作流程,使用指南则详细说明了如何配置开发环境、部署项目以及常见问题的解决方法。 毕业设计参考:对于正在准备毕业设计的学生来说,这些资源包是绝佳的参考材料。每个项目不仅功能完善、结构清晰,还符合常见的毕业设计要求和标准。通过这些项目,学生可以学习到如何从零开始构建一个完整的Web系统,并积累丰富的项目经验。
资源包主要包含以下内容: ASP项目源码:每个资源包中都包含完整的ASP项目源码,这些源码采用了经典的ASP技术开发,结构清晰、注释详细,帮助用户轻松理解整个项目的逻辑和实现方式。通过这些源码,用户可以学习到ASP的基本语法、服务器端脚本编写方法、数据库操作、用户权限管理等关键技术。 数据库设计文件:为了方便用户更好地理解系统的后台逻辑,每个项目中都附带了完整的数据库设计文件。这些文件通常包括数据库结构图、数据表设计文档,以及示例数据SQL脚本。用户可以通过这些文件快速搭建项目所需的数据库环境,并了解各个数据表之间的关系和作用。 详细的开发文档:每个资源包都附有详细的开发文档,文档内容包括项目背景介绍、功能模块说明、系统流程图、用户界面设计以及关键代码解析等。这些文档为用户提供了深入的学习材料,使得即便是从零开始的开发者也能逐步掌握项目开发的全过程。 项目演示与使用指南:为帮助用户更好地理解和使用这些ASP项目,每个资源包中都包含项目的演示文件和使用指南。演示文件通常以视频或图文形式展示项目的主要功能和操作流程,使用指南则详细说明了如何配置开发环境、部署项目以及常见问题的解决方法。 毕业设计参考:对于正在准备毕业设计的学生来说,这些资源包是绝佳的参考材料。每个项目不仅功能完善、结构清晰,还符合常见的毕业设计要求和标准。通过这些项目,学生可以学习到如何从零开始构建一个完整的Web系统,并积累丰富的项目经验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值