4.5. Setting the Focus to a Control with a Validation Error

Problem

You want to set the focus to the first control on your form that has a validation error.

Solution

The solution to this recipe is an extension of the one introduced in Recipe 4.4, where we recommend writing code that generates some client-side JavaScript that calls the focus method of the desired control. For this recipe, we recommend adding some additional JavaScript-generating code tied to the Save button’s click event handler and, when executed, searches for a control with a validation error and sets the focus to that control.

In the code-behind class for the page, use the .NET language of your choice to:

  1. Write some code that is called from the Page_Load method and generates a client-side JavaScript block that calls the focus method of the desired control and sets the control’s initial focus to itself (see Recipe 4.4 for details).

  2. Add additional code to the Save (or equivalently named) button’s click event handler that searches for a control with a validation error and sets the focus to that control.

  3. Use the RegisterStartupScript method of the ClientScript object to register the script block so that it is output when the page is rendered.

Examples 4-16 and 4-17 show routines required to implement the last two steps of this solution.

Discussion

As described in Recipe 4.4, you start implementing this solution by creating a client-side JavaScript block in the code-behind that sets the focus to a desired control and then outputs the block to the rendered page so it is executed when the page is loaded. With this code in place, you can add some additional code to the Save (or equivalently named) button’s click event that determines the first control with a validation error and sets the focus to it via the previously loaded JavaScript code.

This solution relies on the page object containing a collection of the validation controls on the form. The order of the validators in the collection is the same as the order in which they appear in the .aspx file. (The validators should be placed with the controls they validate for this solution to work correctly.)

To get a feel for how to implement this solution, first take a look at the sample application we created for Recipe 4.4 (Examples 4-13, 4-14 through 4-15). Next, consider the code in Examples 4-16 and 4-17, which is added to that application to implement this recipe’s solution.

With the additional code, when the server-side button’s click event is executed, a check is first made to see if the page is valid. If it is, a save operation will be performed. If the page is invalid, the validators will be iterated through until the first invalid one is found. This is determined by examining the IsValid property of each validator control; its value will be false if the control associated with the validator has failed to pass validation.

When an invalid validator is found, the associated control is identified by calling the FindControl method of the validator object. The control is then passed to the setFocusToControl method. Only one control can have the focus, so after an invalid control is found, the for loop is exited.

The client-side validation is disabled in this example to simplify the explanation of how to determine which control has a validation error and how to set the focus to it. If we had kept client-side validation enabled, we would have had to implement the same approach using client-side JavaScript. Though the latter may prove to be the most useful for you, we have avoided it here to keep this recipe lean and to the point.

See Also

Recipe 4.4

Example 4-16. Setting focus to control with validation error (.vb)

'''***********************************************************************
''' <summary>
''' This routine provides the event handler for the save button click
''' event.
''' </summary>
'''
''' <param name="sender">Set to the sender of the event</param>
''' <param name="e">Set to the event arguments</param>
Protected Sub btnSave_ServerClick(ByVal sender As Object, _
								 ByVal e As System.EventArgs)
  Dim validator As System.Web.UI.WebControls.BaseValidator

  If (Page.IsValid) Then
	'process form data and save as required for application

  Else
	'page is invalid so iterate through validators to find the first one
	'with an error
	For Each validator In Page.Validators
	   If (Not validator.IsValid) Then
	     'validator that failed found so set the focus to the control
		 'it validates and exit the loop
		 setFocusToControl(validator.FindControl(validator.ControlToValidate))
		 Exit For
	  End If
	Next validator
  End If
End Sub 'btnSave_ServerClick

Example 4-17. Setting focus to control with validation error (.cs)

///***********************************************************************
/// <summary>
/// This routine provides the event handler for the save button click
/// event.
/// </summary>
///
/// <param name="sender">Set to the sender of the event</param>
/// <param name="e">Set to the event arguments</param>
protected void btnSave_ServerClick(Object sender,
								  System.EventArgs e)
{
   if (Page.IsValid)
   {
	 // process form data and save as required for application
   }
   else
   {
	 // page is invalid so iterate through validators to find the first one
	 // with an error
	 foreach (BaseValidator validator in Page.Validators)
	 {
		if (!validator.IsValid)
		{
		// validator that failed found so set the focus to the control
		// it validates and exit the loop
		setFocusToControl(validator.FindControl(validator.ControlToValidate));
		break;
	  }
     }
   }
} //btnSave_ServerClick

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.