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

}

}

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看REaDME.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 、资源1项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值