Shared Validator Attributes

only for RuBoard

All of the validation controls share a base set of properties and methods . As you go though this chapter, you will see us use them in nearly every example, so we thought it prudent to go over these first. The following quick reference lists and discusses the eight we will be using most often (for a list of all, see the BaseValidator class):

  • ControlToValidate The ID property of the control you wish to have validated by the validation control.

  • IsValid A Boolean value (true or false) indicating whether or not the control which is being validated is valid. True if valid and false if not.

  • ErrorMessage The error message you want displayed to the user if the control is found to be invalid.

  • Text The inner contents of the control.

  • EnableClientScript A Boolean value ( true or false ) indicating whether client-side validation is enabled.

  • Enabled A Boolean value indicating whether the validation control is enabled ”client and server-side validation.

  • Validate Method used to perform validation on the associated INPUT control.

  • Display The display of the validation control when it gives the user an error message. The following three values are acceptable for this attribute:

    • None The validation control isn't displayed inline. If there is not a ValidationSummary control, no error message will be given to the user.

    • Static The validation control is displayed inline and is part of the page layout even when not visible. For instance, if your error message contains a paragraph worth of text, it will take up a paragraph worth of space on the page.

    • Dyanamic The validation control is displayed inline, but doesn't make up part of the page layout until the control is found to be invalid.

Of course many of the validation controls have their own set of properties that are used as well, but we will be going over those in each of the different controls sections.

What Controls Can Be Validated

Not all server controls support the use of validation controls. The following list contains each control that supports the use of validation contols and what property can be validated:

  • RadioButtonList server control SelectedItem.Value

  • DropDownList server control SelectedItem.Value

  • ListBox server control SelectedItem.Value

  • TextBox server control TextBox.Text

  • HtmlInputFile HTML server control HtmlInputFile.Value

  • HtmlSelect HTML server control HtmlSelect.Value

  • HtmlTextArea HTML server control HtmlTextArea.Value

  • HtmlInputText HTML server control HtmlInputText.Value

Server-Side Validation

As previously mentioned, validation occurs on both the client-side (client-side JavaScript) and server-side. So you may be wondering what happens on the server-side. In this section, we'll give you a high-level overview of just that. All the topics discussed in this section will apply to all validation controls. We'll also be giving you a few code examples of some commonly asked questions regarding validation controls, for instance, programmatically affecting validation.

The first thing we want to discuss is when validation occurs on the server. When I say "when validation occurs" I am talking about within the page processing model. The following list is a simplified model of the page processing model after a post back has occured. There is much more to this model, but for our discussion this is what you need to know, because quite frankly, I can talk about the page processing model for hours:

  • The Page and its controls are created.

  • The Page and its controls properties are populated .

  • The Page and its controls are updated to new values based on data the user enters, for example, if the user changes their phone number in a TextBox .

  • The Page.Load is fired .

  • Validation takes place on controls.

  • Event Handling occurs ”This is where events like SelectedIndexChanged , which we saw in the previous chapter, are handled. At this point, you can access the Page.IsValid property (discussed later in chapter).

As you can see, if you try to check the Page.IsValid property in the Page.Load event, it will always return true since validation hasn't occurred yet. You can override this default functionality by invoking the Page.Validate method before checking the Page.IsValid property.

A question that comes up often is how to disable server-side validation? Well, there are a couple ways; first, by using the Validation controls Enabled attribute ( false = disabled, true = enabled ), but the side effect is that client-side validation also is disabled. The second way is overriding the Page.Validate method. The differences between the two methods are you can disable all validation by overriding the Page.Validate method and you can only disable an individual control by using its Enabled property.

Listing 9.1 contains an example of disabling validation by overriding the Page.Validate method. In this example, there is a CheckBox and when its Checked attribute is true , validation occurs; otherwise , validation doesn't occur. This example uses the RequiredFieldValidator .

Listing 9.1 Disabling Validation Controls
 [VisualBasic.NET] 01: <script language="vb" runat="server"> 02: 03:  public overrides sub Validate() 04: 05:   if (validater.Checked) then 06: 07:    mybase.Validate() 08: 09:   end if 10: 11:  end sub 12: 13: </script> [C#.NET] 01: <script language="C#" runat="server"> 02: 03:  public override void Validate(){ 04: 05:   if(validater.Checked) { 06: 07:    base.Validate(); 08: 09:   } 10: 11:  } 12: 13: </script> [VisualBasic.NET & C#.NET] 14: <html> 16:   <form runat="server"> 17:    <center> 18: 19:    <asp:RequiredFieldValidator 20:     runat="server" 21:     ControlToValidate="Required" 22:     id="rfv" 23:     EnableClientScript="False" 24:    > 25:    * Not Valid 26:    </asp:RequiredFieldValidator> 27: 28:    <asp:TextBox 29:     runat="server" 30:     id="Required" 31:    /> 32: 33:    <asp:Button 34:     runat="server" 35:     Text="Validate" 36:    /> 37: 38:    <br> 39: 40:    <asp:CheckBox 41:     runat="server" 42:     id="validater" 43:     text="Validate Page?" 44:    /> 45:    </center> 46: 47:   </form> 48:  </body> 49: </html> 

Because this section is not intended to teach you about validation controls, but rather the validation process, we'll not be discussing the RequiredFieldValidator in this section. Lines 3 “9 contain the Page.Validate method. Within it, I have an if end if statement that checks if the CheckBox is checked or not. If it is checked, then I invoke the base.Validate method, and if it isn't checked then validation doesn't occur.


The base (C#) and mybase (VB) keywords are used to call a method on a base class that has been overridden by another method ”in this case, the Validate method. If I were just to call the Page.Validate method again, an exception would occur because my method would invoke itself.

After the base.Validate method is called, the pages default validation process occurs. Using this functionality enables you to modify each of the validation controls and then revalidate them. For example, you can change all the validation controls IsValid attribute to false and then call base.Validate and each control will be invalid or you can manipulate the values of the controls somehow before they are validated. Beyond disabling page validation, you can override the Page.Validate method to do custom validation.

The Page object has a property you can use to check if the page as a whole is valid. The Page.IsValid property returns a Boolean value indicating if the page is valid. A page is considered valid if every enabled validation controls IsValid property is true . If one controls IsValid property is false , then the whole page is considered invalid.

Another property of the Page I want to go over is the Page.Validators property. This property exposes a ValidatorCollection object, which is an array of all validation controls for the page. For an example on how to use this property, replace the server code from Listing 9.1 with that contained in Listing 9.2. This code loops through the ValidatorCollection and outputs whether or not the individual validation controls IsValid property value.

Listing 9.2 Looping through the ValidatorCollection
 [VisualBasic.NET] 01: <script language="vb" runat="server"> 02: 03:  public overrides sub Validate() 04: 05:   if (validater.Checked) then 06: 07:    mybase.Validate() 08: 09:   end if 10: 11:   CheckValidators() 12: 13:  end sub 14: 15:  sub CheckValidators() 16: 17:   dim ValCol as ValidatorCollection = Page.Validators 18:   dim IVal as IValidator 19: 20:   for each IVal in ValCol 21: 22:    dim sb as new StringBuilder("<center>") 23:    sb.Append("Control is Valid: ") 24:    sb.Append((CType(IVal,RequiredFieldValidator).IsValid)) 25:    sb.Append("</center>") 26:    Response.Write(sb.ToString()) 27: 28:   next IVal 29: 30:  end sub 31: 32: </script> [C#.NET] 01: <script language="C#" runat="server"> 02: 03:  public override void Validate(){ 04: 05:   if(validater.Checked) { 06: 07:    base.Validate(); 08: 09:   } 10: 11:   CheckValidators(); 12: 13:  } 14: 15:  void CheckValidators(){ 16: 17:   ValidatorCollection ValCol = Page.Validators; 18: 19: 20:   foreach(IValidator IVal in ValCol) { 21: 22:    StringBuilder sb = new StringBuilder("<center>"); 23:    sb.Append("Control is Valid: "); 24:    sb.Append(((RequiredFieldValidator) IVal).IsValid); 25:    sb.Append("</center>"); 26:    Response.Write(sb.ToString()); 27: 28:   } 29: 30:  } 31: 32: </script> 

In Listing 9.2, I created a CheckValidator (lines 15 “30) method which is invoked from the Validate (lines 3 “13) method. Within the CheckValidator method, I have a for each statement which loops through the ValidatorCollection object (lines 20 “28). Notice the IValidator object on line 20 ”the ValidatorCollection is made up of references to these objects ”each one being a validation control located in the page. The IValidator class defines all the properties and methods that all validation controls must implement.

Client-Side Validation

Client side validation comes in the form of automatically generated JavaScript and most of the functionality is kept in the WebUIValidation.js that is distributed with ASP.NET. Because of this fact, support for client side validation is browser independent and this is yet another reason why server-side validation takes place even if client script is disabled. Client-side validation can be disabled by setting a single property available for all validation controls:

  • EnableClientScript A Boolean value ( true or false ) indicating whether client-side validation is enabled.

When client-validation is enabled, it's important to know what is going on behind the scenes. Initial validation occurs as the user moves from field to field ( INPUT control to INPUT control). If all the validation controls are valid and the user submits the page (clicking a submit button), the page then will be posted back to the server and server-side validation takes place. If one or more of the controls are not valid when the user tries to submit the page, the submit is cancelled and all the invalid validators become visible. If there is a ValidationSummary control, which we will examine in a later section, it will become visible as well with a list of errors messages. If the ValidationSummary has message box output, then a client-side message box with a list of errors will be generated.

You might run into a situation where you need multiple buttons on a page. You might not want to submit the form for one of those buttons , but if you don't take preventative measures, a user could get stuck on that form because it is not validated. An example would be if you not only have information collection forms on a page, but you also have fields for search functionality.

Listing 9.3 contains code example illustrating how to cancel validation if a user clicks on one button, but how to make it work if he clicks on another. In this example, I am using a RequiredFieldValidator , a TextBox , and three Buttons . The reason for the three buttons is I want to show you two ways to disable client script. The first is through a client-side function call and the second is by setting the Buttons CausesValidation attribute to false . By settting the CausesValidation attribute to false , a post back to the server still occurs.

Listing 9.3 Disabling Client-side Validation
 01: <html> 02:  <head> 03:   <script language="c#" runat="server"> 04: 05:    void ButtonTwo_Click(Object sender, EventArgs e){ 06:     lblMessage.Text = "Validation Was Cancelled - PostBack Occured"; 07:    } 08: 09:   </script> 10: 11:   <script language="JavaScript"> 12: 13:    function ButtonOne_Click(){ 14: 15:     document.all["lblMessage"].innerText = "Validation Was Cancelled - No PostBack"; 16: 17: 18:    } 19: 20:   </script> 21:  </head> 22:  <body Style="font-size:10"> 23:   <form runat="server"> 24:    <center> 25: 26:    <h3>RequiredFieldValidator</h3> 27: 28:    First Name:&nbsp;&nbsp; 29: 30:    <asp:TextBox 31:     id="txtFirstName" 32:     runat="server" 33:    /> 34: 35:    <asp:RequiredFieldValidator 36:     id="rfv" 37:     Runat="Server" 38:     ControlToValidate="txtFirstName" 39:     Display="Dynamic" 40:    > 41:     * Required Field 42:    </asp:RequiredFieldValidator> 43: 44:    <p> 45: 46:    <asp:Button 47:     id="ButtonTwo" 48:     runat="server" 49:     Text="Submit" 50:    /> 51: 52:    <input type="button" 53:     id="ButtonOne" 54:     value="Cancel One" 55:     runat="server" 56:     OnClick="ButtonOne_Click()" 57:    /> 58: 59:    <asp:Button 60:     runat="server" 61:     CausesValidation="false" 62:     Text="Cancel Two" 63:     OnClick="ButtonTwo_Click" 64:    /> 65: 66:    <p> 67: 68:    <asp:Label 69:     runat="server" 70:     id="lblMessage" 71:     name="lblMessage" 72:     ForeColor="Red" 73:     Font-Bold="true" 74:    /> 75: 76:    </center> 77:   </form> 78:  </body> 79: </html> 

As previously mentioned, there is a TextBox control (lines 30 “33) in Listing 9.3, which is wired to a RequiredFieldValidator (lines 35 “42) effect: The TextBox must be filled out to be valid. There are three possible buttons to click on in the page. The first, lines 46 “50, submits the page and validation occurs ”both client and server-side validation. The HtmlButton , lines 52 “57, has an OnClick value of ButtonOne_Click ”a client side JavaScript function found on lines 13 “18. Within the ButtonOne_Click function, you can do what you wish. In this example, I simply write out to the page. The important point is that the form isn't automatically submitted (you can use the OnServer). The third button (lines 59 “64) uses one of its own attributes to prevent validation ”on both the server and client ” CausesValidation attribute. CausesValidation expects a Boolean value which indicates whether or not validation should occur when that particular button is clicked ”default is true .

Now that you have a high-level view on how validation works, and some of their shared attributes, let's go over each of the individual controls from the validation controls suite.

only for RuBoard

Programming Data-Driven Web Applications with ASP. NET
Programming Data-Driven Web Applications with ASP.NET
ISBN: 0672321068
EAN: 2147483647
Year: 2000
Pages: 170

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: