Resources

Input validation in ASP.NET websites

When data sent form browser to server need to ensure it is valid.

Users expect feedback and assistance to enter valid data.

ASP.NET provides mechanisms for bot client and server side validation.

Client side validation is convenient for users, but is not a security feature.

Improves performance by checking data before submission to server.

Malicious user can easily circumnavigate.

Validation Controls

Found in Visual Studio Toolbox.

Add same way as other controls.

  1. Open page in Design View & add input controls requiring validation
  2. Drag desired validation control next to (or near) input control to validate
  3. Set ID property of validation control - for readability make it similar to input control it is validating, e.g. NameTextBoxValidator
  4. Set ControlToValidate property on validation control to control being validated
  5. Set ErrorMessage to something meaningful for the user. Typically displayed in ValidationSummary control on the page
  6. Set Text property to display at the validation control location if the validation fails. If plan to use ValidationSummary control set Text property to something short, such as *
  7. Set tooltip property to something similar to ErrorMessage. The tooltip will be displayed when user points to validation control after validation fails.
  8. Set Display property to None to prevent Text property being displayed. Set to Static to leave blank space where message will appear. Set to Dynamic to reformat ASP.NET output around Text when validation fails.
  9. Optionally add ValidationSummary to display validation error messages in one location after user has triggered page-level validation by clicking a submit button. Useful in page crowded with other controls. Typically placed near submit button. If ShowMessageBox property is true then control will display a pop-up message.

Server-Side Validation

Validation controls work in concert with Page object. ASP.NET uses Page class and validation controls to ensure incoming data is valid.

Page class Validators property contains collection of validation controls defined on page.

The Pages Validate method causes the page to check each validation control.

Validate method called automatically after Load event handler method executed.

Can check if page is Valid by checking Page.IsValid property (after the page has loaded).

Should check Page.IsValid property in every event handler to determine if code should run.

Client-Side Validation

ASP.NET writes client-side validation code for validation control on page.

Associated JavaScript executes when focus gained / loss by controls on page.

Turned on by default.

Can turn off for specific controls by setting EnableClientScript property to false.

Can use Focus method of control to set focus to specific control when page loads. Focus method uses JavaScript to set focus when page loads.

Validation controls have SetFocusOnError property that when true causes invalid control to receive focus.

When to cause validation

Client side validation is convenience for users.

Primary benefit is stopping page from being posted back until all client-side validation passes.

Can be a problem in some circumstances, e.g. clicking cancel or help button when page not in valid state. Avoid problem by setting CausesValidation property to false for controls that should bypass validation.

Validation Groups

May not want entire page to be validated as a whole.

May want to break up into sections and have them validated independently, e.g. form with multiple sections.

Validation controls support ValidationGroup property, which is assigned string value. Same property also present on controls causing postback. When control performs postback, validation controls with matching ValidationGroup property are validated.

On server the Page.IsValid property only reflects validity of controls that have been validated. By default these are controls in same ValidationGroup. Can call controls Validate method to add control to set of controls the IsValid property reports on.

Overload of Page.Validate method accepts a string to specify ValidationGroup to check.

The Page.GetValidators method accepts string identifying ValidationGroup and returns list of controls in that validation group.

RequiredFieldValidator Control

Ensures users has entered value into field.

Provides InitialValue property that when set ensures the user has changed field value.

CompareValidator Control

Performs comparison using operators like greater than or less than (set via Operator property) to compare user data with constant value provided, or another control.

ValueToCompare property provides constant used to perform comparison against - ignored for DataTypeCheck comparisons.

CompareToControl property allows comparisons to be made against value of another control.

Can also check data entered is of certain data type, e.g. date or number, by setting Type property to required data type. Can limit to type checks by setting Operator property to DataTypeCheck.

RangeValidator Control

Ensures value entered within predefined range, specified by MinimumValue and MaximumValue.

RegularExpressionValidator Control

The ValidationExpression property specifies a regular expression that the control being checked must pass.

CustomValidator Control

Used to create own validation mechanism.

Custom Client-Side Validation

Custom validation JavaScript needs to participate in data validation framework.

Function must have signature of function ClientFunction(source, arguments)

The source parameter contains reference to validation control performing validation.

The arguments parameter contains an object with a Value property that contains data to be validated.

Validation logic should set arguments.IsValid to true (valid) or false (invalid).

Used for complex scenarios that cannot be covered by regular expressions, e.g. calling web service to make sure user name available without requiring post back to take place.

Custom Server-Side Validation

CustomValidator can work client-side, server-side or both.

To implement server side handle the ServerValidate event of the CustomValidator - same way implement event handler for any control.

Two parameters provided to handler:

Server side validation does not need to provide exactly same validation as client side, e.g. client side might check 5 digit user id is within an acceptable range whilst server side will perform database lookup to verify it actually exists.

Downloads