Examining the RequiredFieldValidator Validation Control


When we're prompting a user for input, the input can be divided into two categories: required input and optional input. Required input is the set of input that the user must provide, whereas optional input is the set of input that the user may choose to provide or not to provide. To ensure that the user provides a response for a particular input, we can use a RequiredFieldValidator Web control.

To add a RequiredFieldValidator validation Web control to an ASP.NET web page, all that we have to do is drag and drop the control from the Toolbox onto the page, just like we do with any other Web control. Go ahead and drag the RequiredFieldValidator Web control from the Toolbox onto the designer; specifically, place the Web control immediately to the right of the first TextBox Web control.

By the Way

All of the validation controls are grouped within the Validation section of the Toolbox.


When you drag and drop the RequiredFieldValidator validation control onto the designer, your screen should look similar to Figure 12.3. Although the image in this book doesn't show it, the text "RequiredFieldValidator" appears in a red font.

Figure 12.3. A RequiredFieldValidator has been added to the ASP.NET web page.


Specifying What Web Control the Validation Web Control Is Validating

Realize that the validation Web controls are designed to validate input for a particular input Web control. By input Web control, I mean a Web control that is used to collect user input, such as the TextBox Web control.

All validation Web controls contain a ControlToValidate property, which specifies what input Web control the validation Web control is validating. For example, because we want to require users to provide their name in the ValidationControlTestBed.aspx ASP.NET page, we need to add a RequiredFieldValidator and set the RequiredFieldValidator's ControlToValidate property to name, the ID of the Web control that has a required field.

Note that each validation Web control that you add to your ASP.NET page can validate only a single input Web control. Therefore, if in our ValidationControlTestBed.aspx ASP.NET web page, we had three required input fields (say name, age, and Social Security number), we would need three RequiredFieldValidator validation controls on the page.

For now, let's assume that the only required field is the name input. Therefore, we need to set the ControlToValidate property of the RequiredFieldValidator that we just added to the page to name. To do this, click on the RequiredFieldValidator, which will load its properties in the Properties window.

Next, click on the ControlToValidate property, which will show a drop-down list of the various Web controls on the page (see Figure 12.4). Go ahead and select the name option from the list.

Figure 12.4. Select the Web control you want the RequiredFieldValidator to validate.


One important word of warning: If you set the ControlToValidate property to a specific Web control and then change that Web control's ID property, you will get an error when visiting the ASP.NET page through a browser (see Figure 12.5). The reason is that the validation Web control's ControlToValidate property is not automatically updated when the Web control it is to validate has its ID property changed. Therefore, if you change a Web control's ID property after you have added validation controls to the page, make sure to double-check that the ControlToValidate properties for your validation controls map to the correct, current value of the ID property of the Web control it is set to validate.

Figure 12.5. An error will occur if the validation Web control's ControlToValidate property is incorrectly set.


Specifying What Error Message to Display for Invalid Input

Along with a ControlToValidate property, all validation Web controls contain an ErrorMessage property. This string property contains the text that is displayed when the user's input fails to meet the validation requirements. Typically, this text should provide a brief explanation as to the problem with the user's input and what she needs to do to fix it.

For example, for a RequiredFieldValidator, you might want to set the ErrorMessage to "You must provide a value for input", where input is the name of the input that the user is required to provide. Another common ErrorMessage value for RequiredFieldValidators is an asterisk. As you probably know from first-hand experience, many websites place asterisks next to required form fields.

For the ValidationControlTestBed.aspx ASP.NET page, go ahead and set the RequiredFieldValidator's ErrorMessage to You must provide your name. After you enter this value, the text for the RequiredFieldValidator in the designer will change to the new ErrorMessage value (see Figure 12.6).

Figure 12.6. The designer, after the RequiredFieldValidator's ErrorMessage property has been set.


Testing the ASP.NET Page

Now that we have specified the ControlToValidate and ErrorMessage properties, the RequiredFieldValidator will inform users if they forget to provide a value for the name text box. To test this, view the ValidationControlTestBed.aspx page through a browser. Figure 12.7 shows this web page when first visited.

Figure 12.7. The ValidationControlTestBed.aspx web page, when first visited.


Note that there is a slight difference in the appearance of the web page when viewed through a browser and when shown in the Design view. Namely, the RequiredFieldValidator is not displayed.

Now, go ahead and click on the Click Me button without entering any text into the name text box. What happened? If you are using a browser that supports client-side script (virtually all modern web browsers), clicking the button did not cause the form to be submitted, but instead caused the message "You must provide your name" to appear next to the name text box. If you are using a browser that does not support these features (or has them disabled), clicking the button caused the form to submit, but, upon postback, the message "You must provide your name" was displayed next to the name text box.

Figure 12.8 shows the ValidationControlTestBed.aspx page after the Click Me button has been clicked when there was no input entered into the name text box.

Figure 12.8. The message "You must provide your name" appears next to the name text box.


Now, enter some text into the name text box. After you have done this, click on a different text box so that some other text box receives the focus. If you are using a browser that supports it, clicking out of the name text box after entering text into the name text box will cause the "You must provide your name" message to magically disappear! If you are using a browser that does not support such features, the message will still be present; however, if you submit the form by clicking the Click Me button, upon postback the message will have disappeared.

Client-side and Server-side Validation

What's going on here? Why does the validation error message behave differently depending on what browser is being used? The difference arises due to the fact that validation Web controls include client-side validation for browsers that have such capabilities.

Client-side validation involves JavaScript code that runs on the user's web browser. When the user tabs or clicks out of a text box, a piece of JavaScript code that determines whether the input provided is valid is run on the user's web browser; if the data is invalid, the client-side script automatically displays the validation Web control's ErrorMessage property value.

Browsers that do not have client-side scripting features or have them disabled, on the other hand, employ just server-side validation. Server-side validation, as the name implies, is validation that occurs in code that is executed on the web server. This is the reason why with such a browser the "You must provide your name" message does not disappear, even after text has been entered into the name text box, until the user submits the form. For the message to disappear, the ASP.NET page must be posted back, which, as you already know, causes the ASP.NET page to be fetched from the web server again. When this page is requested from the web server, the user's input can be checked there, and it can be determined whether the user's input meets the validation criteria.

By the Way

All validation controls, regardless of what browser is being used, perform server-side validation checks. That means that, for both the client-side and server-side, checks are performed for browsers that can support client-side script. Server-side validation is included even when client-side validation is present because client-side validation can be circumvented by simply disabling JavaScript in an uplevel browser.


Client-side validation's main advantage over server-side validation is that it provides immediate feedback to the user without requiring a postback to the web server. This has the advantage of saving the user time, especially if he is on a slow connection, because it does not require a roundtrip to the web server.

By the Way

To learn more about client-side validation, check out the article "Form Validation on the Client Side," at http://www.sitepoint.com/article/form-validation-client-side.


Programmatically Determining Whether the User's Input Is Valid

As we have seen, by simply setting the ControlToValidate and ErrorMessage properties of the validation Web controls, these controls will automatically alert the user if her input is in an improper format. But how can we determine whether all of the user's input is valid programmatically?

Typically, we will want to process the user's input in some fashion; for example, in previous hours we have seen how to create a mortgage cost calculator and a BMI calculator. In both examples we needed to perform some mathematical computations on the user's input. Of course, we don't want to perform these calculations unless the data entered by the user is valid.

To determine programmatically whether the user's input is valid, we can check the Page.IsValid property. The Page.IsValid property returns true only if all validation Web controls on the ASP.NET page have indicated that the input entered into its respective input Web control has been entered in the proper format. Put another way, if any one user's input is not valid, Page.IsValid will be False.

To demonstrate using this property, let's create an event handler for the Button Web control's Click event. Recall that when we create an event handler for the Click event, the event handler's code will be executed every time the Web form is posted back. To create an event handler for the Click event, simply double-click on the button in the Design view.

Next, enter the following code into the generated Click event handler:

If Page.IsValid then   'User input is valid   results.Text = "Input is valid..." Else   'There is at least some invalid input   results.Text = "Input is <b>not</b> valid..." End If 


A quick examination of the code reveals that if the Page.IsValid property is true, then the string "Input is valid..." will be displayed; if there is any invalid input, however, the string "Input is not valid..." will be displayed.

This behavior can be seen in Figures 12.9 and 12.10. Figure 12.9 shows the ValidationControlTestBed.aspx ASP.NET page when no input has been entered into the name text box and the form has been submitted. Note that the message "Input is not valid..." is displayed at the top of the web page. Figure 12.10 shows the same ASP.NET page after the user has entered some value into the name text box and has submitted the form. Here, the message "Input is valid..." is displayed.

Figure 12.9. The form has been submitted with invalid user input.


Figure 12.10. The form has been submitted, and all of the user input is valid.


If you are visiting the page with a browser that supports client-side script, you will likely not be able to submit the form without entering a value into the name text box. The reason is that the validation controls render client-side validation logic that prevents a postback until the data is valid. Therefore, in browsers that support client-side script, the server-side Click event handler won't run until the user enters valid data.

Given the very small percentage of users with browsers that don't support client-side script, you might reason that you need not bother with checking the Page.IsValid property in the Button's Click event handler. However, you should always check to ensure that the page is valid before working with the user-submitted data. A nefarious user can easily circumvent the client-side validation checks. (In creating Figure 12.9, I configured Internet Explorer to treat http://localhost as a Restricted Site; therefore, it automatically prevented JavaScript from running, allowing me to cause a postback even when I had failed to provide a name.)

To summarize, you should always check the results of the server-side validation. Client-side validation, which is provided free in browsers that support it, is simply an added bonus. Regardless of whether your users are visiting with such browsers, be sure to always check the Page.IsValid property before working with the data submitted.

Summarizing the Basic Validation Control Features

We started with a discussion of the RequiredFieldValidator and quickly turned to the common properties, features, and semantics of the validation Web controls in general. Before we move on to examining the other validation Web controls, let's take a moment to summarize the common features of validation controls.

First, all validation Web controls are designed to validate a single input Web control. The input Web control a given validation Web control validates is specified via the validation control's ControlToValidate property.

All validation controls also contain an ErrorMessage property, which specifies the text that is displayed if the input is invalid. The actual validation behaves differently depending on the browser being used by the visitor. If the user has a capable browser, the user's experience is enhanced through the use of client-side validation, as well as server-side validation. For nonsupporting browsers, however, only server-side validation occurs.

Finally, to determine programmatically whether the input entered by a user is valid, we can refer to the Page.IsValid property.




Sams Teach Yourself ASP. NET 2.0 in 24 Hours, Complete Starter Kit
Sams Teach Yourself ASP.NET 2.0 in 24 Hours, Complete Starter Kit
ISBN: 0672327384
EAN: 2147483647
Year: 2004
Pages: 233

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net