You can create a manual validation in one of the three ways:

– Use your own code to verify values. In this case, you will not use any of the ASP.NET validation controls.

– Disable the EnableClientScript property for each validation control. This allows an invalid page to be submitted, after which you can decide what to do with it depending on the problems that may exist.

– Add a button with CausesValidation set to false. When this button is clicked, manually validate the page by calling the Page.Validate() method. Then examine the IsValid property, and decide what to do.

 

The next example uses the second approach. The web page used is looks like in the article How to use RangeValidator control in ASP.NET 4.0. To try this example, you should set the EnableCientScript property of each validator to false. Then, you can use the code in this event handler to check for invalid values.

 

protected void cmdOK_Click(Object sender, EventArgs e)

{

string errorMessage = “<b>Mistakes found:</b><br />”;

// Search through the validation controls.

foreach (BaseValidator ctrl in this.Validators)

{

if (!ctrl.IsValid)

{

errorMessage += ctrl.ErrorMessage + “<br />”;

// Find the corresponding input control, and change the

// generic Control variable into a TextBox variable.

// This allows access to the Text property.

TextBox ctrlInput = (TextBox)this.FindControl(ctrl.ControlToValidate);

errorMessage += ” * Problem is with this input: “;

errorMessage += ctrlInput.Text + “<br />”;

}

}

lblMessage.Text = errorMessage;

}

 

The next picture shows the effect of implemented code:

 

Manual validation example

Manual validation example

In this example an advances technique Page.FindControl() method is used, because the ControlToValidate property of each validator simply provides a string with the name of a control, not a reference to the actual control object. To find the control that matches this name, you need to use FindControl() method. To access all the properties of your control, you need to cast it to the appropriate type, because the FindControl() method returns a generic Control reference.