Professional Documents
Culture Documents
C#validationcontrols
C#validationcontrols
Validation server controls are a series of controls that help you validate the data that the user enters into the other controls that are provided with ASP.NET. They determine whether the form can be processed based upon the rules that you define in the validation server controls.
Looking at Validation
One of the most common elements of Web pages is a form in which the user can input data that is posted back to the server. These forms are made up of different types of HTML elements that are constructed using straight HTML, HTML server controls, or Web server controls. A variety of HTML elements, such as text boxes, check boxes, radio buttons, drop-down lists and more, can be used in forms. Often when your ASP.NET applications are collecting information from a user, you want to ensure that the data that you collect is valid. Some users are not interested in spending enough time to enter the correct information into a form, and in some cases, users might even intentionally enter false information to gain access or get past a certain step in your application's workflow process. One of the first steps is to understand what validating data means. Validating, in this case, does not mean that if John Doe types his name into the form field of a text box as Fred Doe the computer sends an alert to inform you that the data is untruthful. No, we still do not have the capability to find out whether a statement is true. Validation is testing to determine whether the user entered something into the field. After you determine that something was entered, you can then also check to see whether what was entered is a number or a character and if it is in the correct format. From there, you can compare user input in different fields or against values that might be held in other repositories, such as a database. You can check for many types of information, as you learn in the rest of this article. Data collection on the Internet is one of its most important features, so you must make sure that the data you collect has value and meaning. You ensure this by eliminating any chance that the information collected does not abide by the rules you outline.
Some sites on the Internet don't carry this inputted information back to the form page, and the user is then required to enter all the information into the form a second time. Obviously, this may cause people to leave your site for another. The bad thing about server-side validation is that it requires trips back and forth to the server. This takes a lot of resources and makes for a slower-paced form for the user. Nothing is more annoying to a user who is on a dial-up connection than clicking the Submit button on the form and then waiting for 20 seconds to find out that they didn't enter their password correctly. The other option for form validation is to put some client-side JavaScript or VBScript at the top of the ASP page that checks if the information in the fields is correct. This takes care of the problem of making unnecessary trips to the server, but it requires another language to learn and manage. JavaScript is a great language, but takes a lot of time to master, and there are always problems getting your JavaScript code to work on different browsers. Listing 1 shows you an example of using client-side JavaScript to perform form validation.
This sample piece of JavaScript does some validation, but it doesn't check for all the in-formation that you might need on the form you are building. This piece of code determines only whether the user entered anything at all in all five fields within the form. It does not determine whether the user entered an actual e-mail address within the e-mail address text box, whether the user entered a number between two given numbers, or whether the password and the confirm password text boxes match. After awhile, you can see that you need many JavaScript functions to obtain the level of form validation required.
You can also customize validation for your own needs. Then, if there are any errors in the form data, these validation server controls enable you to customize the display of error information on the browser. You place validation server controls on your page as you would any other type of controls. After the user submits the form, the user's form information is sent to the appropriate validation control, where it is evaluated. If the information doesn't validate, the control sets a page property that indicates this. After all the form information is sent to all the validation server controls, if one or more of the validation server controls cannot validate the information sent to it, the entire form input is found to be invalid, and the user is notified. Table 1 describes each of the six validation server controls. Table 1: Available validation server controls
Description
Ensures that the user does not skip a form entry field Allows for comparisons between the user's input and another item using a comparison operator (equals, greater than, less than, and so on)
RangeValidator
Checks the user's input based upon a lower- and upper-level range of numbers or characters
RegularExpressionValid Checks that the user's entry matches a pattern defined by a regular ator expression. This is a good control to use to check e-mail addresses and phone numbers CustomValidator ValidationSummary Checks the user's entry using custom-coded validation logic Displays all the error messages from the validators in one specific spot on the page Not all button clicks are equal Normally, in a series of HTML form elements, there is some sort of Button, ImageButton, or LinkButton control on the page that submits the form and causes the validation to initiate. This might not be the functionality that you are always looking for in your Web forms. You may not want each and every button on the ASP.NET page to initiate validation.
For instance, you might have a Cancel or Reset button on the Web page. If the user clicks one of these buttons, you don't want that button click to validate the contents contained in the Web form. To prevent this, you have to set the CausesValidation property for the control to False.
<%@ Page Language="C#" %> <script runat="server"> void Button1_Click(Object sender, EventArgs e) { Label1.Text = "Page is valid!"; } </script> <html> <head> </head> <body> <form runat="server"> <p> <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Required!" ControlToValidate="TextBox1"> </asp:RequiredFieldValidator> </p> <p> <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button>
Run this page and then omit putting a value in the text box. When you click the button, you get a result similar to that shown in Figure 1.
Figure 1: Causing the RequiredFieldValidator server control to fire There are a few things to be aware of when using the RequiredFieldValidator server control in your ASP.NET pages. First of all, the most important property of this validation control is the ControlToValidate property. The value assigned to this control needs to be the value of the id property for the control to which you want to link the RequiredFieldValidator control. You can link only one RequiredFieldValidator server control to any other server control on the page. For instance, if you have three required TextBox controls on your ASP.NET page, you need three separate RequiredFieldValidator controls to make sure that they are all required. The second property of this control is the ErrorMessage property. This is the text that appears where the RequiredFieldValidator control is located on the ASP.NET page if the TextBox is left empty. Instead of using the ErrorMessage property, you can also use the Text property:
As you run this simple page, notice a few things. First of all, if you are running a client that is considered an upper-level browser (for example, Internet Explorer 4.0 or better), the code generated to perform the validation is client-side. To see this, right-click the page, and then click View Source. You see JavaScript in the code of the page. The JavaScript in the code of the page means that the required field checking against the text box on the page is done client-side. To test this, simply click the button on the page, and you see the Required! error message displayed. Next, enter a value in the TextBox control, and then press TAB. The RequiredFieldValidator server control is then triggered. By default, red text is used for the error messages that are shown by these validation server controls. As with most of the ASP.NET server controls, however, you can change the style of the controls by changing the properties of the control in code or within the designer. For instance, you can apply a more complex style as illustrated here:
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ControlToValidate="TextBox1" BackColor="DarkGray" BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" ForeColor="White" Font-Bold="True" Font-Names="Verdana" Font-Size="X-Small"> Enter something </asp:RequiredFieldValidator>
Using code similar to the preceding, you can get a more elaborate result, as shown in Figure 2.
Figure 2: A RequiredFieldValidator control with a little more style Note The RequiredFieldValidation server control works with most HTML form elements except for check boxes. You cannot validate against the CheckBox or CheckBoxList server controls using the RequiredFieldValidator server control. Instead you need to use the CustomValidator server control. An example of this is shown later in this article.
<asp:TextBox id="TextBox1" runat="server">Hello</asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please change value" ControlToValidate="TextBox1" InitialValue="Hello"> </asp:RequiredFieldValidator>
In this example, the single text box has a default value of Hello. The value you place here can be from any source, even a dynamic source. There is also a RequiredFieldValidator server control that is assigned to validate this text box. In this case, you want the user to change the initial value of this control to something other than the default value of the InitialValue property Hello. You can also populate the value of this property from a dynamic source, just as you can populate the TextBox server control from a dynamic source.
Because of the InitialValue property, if the user tries to submit the form without changing the value in the text box, the RequiredFieldValidator control fires and the form does not post to the server. If the user changes the value in the text box and submits the form, this RequiredFieldValidator control does not fire and the form is posted.
Requiring a Value Change and Disallowing Empty Values at the Same Time
When using the RequiredFieldValidator control against a text-based control such as a TextBox control, you can use the InitialValue property. The form validation fails if the value contained in the associated control is not changed from this value. If you use this kind of construct, however, the user can change the value of the text box in any manner to get past the validation. He or she can even empty the text box of any value, and it still passes the validation process. In some situations, you can require the user not only to change the initial value of the text box, but also to input some value so that it is not empty. To do this, use two RequiredFieldValidator server controls. The first RequiredFieldValidator server control uses the InitialValue property to ensure that the user changes the default value in the text box that the control is associated with. The second RequiredFieldValidator control validates that the same text box is not left empty, as illustrated in Listing 4. Listing 4: A single TextBox control with two RequiredFieldValidator controls Copy
<asp:TextBox id="TextBox1" runat="server">Hello</asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please change value" ControlToValidate="TextBox1" InitialValue="Hello"> </asp:RequiredFieldValidator> <asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="Do not leave empty" ControlToValidate="TextBox1"> </asp:RequiredFieldValidator>
Listing 5: Using the RequiredFieldValidator server control with the Drop-DownList server control Copy
<asp:DropDownList id="DropDownList1" runat="server"> <asp:ListItem Selected="True">Select a profession</asp:ListItem> <asp:ListItem>Programmer</asp:ListItem> <asp:ListItem>Lawyer</asp:ListItem> <asp:ListItem>Doctor</asp:ListItem> <asp:ListItem>Artist</asp:ListItem> </asp:DropDownList> <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Please make a selection" ControlToValidate="DropDownList1" InitialValue="Select a profession"> </asp:RequiredFieldValidator>
Using this kind of construct enables you to place a description of the actions required in the dropdown list and also requires the user to make a selection from the choices. To get past the validation process, the user must make a selection other than the Select a profession choice. If the user doesn't enter a profession, an error message is returned (see Figure 3). It takes a lot of code to write your own JavaScript function for this procedure, and that JavaScript also has to be browser-independent. With ASP.NET, the RequiredFieldValidator server control takes care of that.
String, Integer, Double, Date, or Currency in the CompareValidator control to make sure that
the user's input into the field is the specified type.
<%@ Page Language="C#" %> <script runat="server"> void Button1_Click(Object sender, EventArgs e) { Label1.Text = "Passwords match"; } </script> <html> <head> </head> <body> <form runat="server"> <p> Password<br> <asp:TextBox id="TextBox1" runat="server" TextMode="Password"></asp:TextBox> <asp:CompareValidator id="CompareValidator1" runat="server" ErrorMessage="Passwords do not match!" ControlToValidate="TextBox2" ControlToCompare="TextBox1"></asp:CompareValidator> </p> <p> Confirm Password<br> <asp:TextBox id="TextBox2" runat="server" TextMode="Password"></asp:TextBox> </p> <p> <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Login"></asp:Button> </p> <p> <asp:Label id="Label1" runat="server"></asp:Label> </p> </form> </body> </html>
In this example, the Web form uses two TextBox server controls. One is for the user to enter the password, and the second TextBox control requires the user to enter the password again to ensure they didn't mistype the original. By using the CompareValidator server control, you guarantee that they are equal strings. If they are not equal, the page returns an error message (see Figure 4). If they are equal, your page submits as valid.
Figure 4: In this example, the user mistyped the password and got an error message.
Age: <asp:TextBox id="TextBox1" runat="server" MaxLength="3"> </asp:TextBox> <asp:CompareValidator id="CompareValidator1" runat="server" ErrorMessage="You must enter a number" ControlToValidate="TextBox1" Type="Integer" Operator="DataTypeCheck"></asp:CompareValidator>
In this example, the user must enter an integer in the text box; otherwise, the CompareValidator server control fires and displays an error message on the page. By giving the Type property of
the CompareValidator server control a value of Integer, you ensure that the value entered in the text box conforms to this .NET Framework data type. You also have the option of not only comparing values against specific data types, but also ensuring that values are valid when compared against certain constants (see Listing 8). Listing 8: Comparing values against constants for validity
Age: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> <asp:CompareValidator id="CompareValidator1" runat="server" Operator="GreaterThan" ValueToCompare="18" ControlToValidate="TextBox1" ErrorMessage="You must be older than 18 to join" Type="Integer"></asp:CompareValidator>
In this case, a few checks are made against any value that the user types in the text box. The first is based on the Type property in the CompareValidator server control. The Type property has the value of Integer, therefore any value placed in the text box needs to conform to this .NET Framework data type. If the user enters a string into the text box, the form submission is invalid. The next property is the Operator property. This property has a value of GreaterThan, meaning that for the form submission to be valid, the value entered in the text box has to be greater than the value that is assigned to the ValueToCompare property. For this CompareValidator server control, the ValueToCompare property has a value of 18. This means that the value entered in the text box on the page must be an integer greater than 18. If it does not meet these criteria, the value is considered invalid, and the CompareValidator server control displays an error message in the browser. In the situation shown in Listing 8, you are not comparing two fields in the form; instead, you are comparing one field against a value that you have specified in code. The Operator property can contain one of the following values:
For instance, imagine that you have a text box where you want end users to enter their ages. Instead of being greater than or less than a specific constant, you want the values entered to be between a specific range of numbers. For this, you use the RangeValidator server control, as illustrated in Listing 9. Listing 9: Using the RangeValidator server control to work with a range of numbers
Age: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> <asp:RangeValidator id="RangeValidator1" runat="server" ControlToValidate="TextBox1" Type="Integer" ErrorMessage="You must be between 30 and 40" MaximumValue="40" MinimumValue="30"></asp:RangeValidator>
In this case, the user should enter a value between 30 and 40 in the text box. If some number is entered that is outside of this range, the RangeValidator server control fires an error message and considers the form submission invalid. The Type property enables you to make comparisons against many different .NET Framework types, such as String, Integer, Double, Date, and Currency. These choices enable you to do a number of range comparisons. For instance, you can use the Currency value in the Type property to retrieve monetary-value entries that are within a certain range. You can also use the Date value for the Type property to make sure that the entry is between specific date ranges. Also, just as you can use the String data type in the CompareValidator server control, you can use the String data type with the RangeValidator server control to make sure that the value entered falls within a specific range of characters. For example, if the user is entering her last name, and you want only people with last names starting with M and P to proceed, you can easily do this by using the RangeValidator server control, as illustrated in Listing 10. Listing 10: Comparing an entry to a range of characters
Last name: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> <asp:RangeValidator id="RangeValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Your last name needs to be between M and P" MaximumValue="Q" MinimumValue="M"></asp:RangeValidator>
In the example in Listing 10, the value is being checked against a range that is specified by using the MaximumValue and MinimumValue properties. Notice, in this example, that the Type property is not specified. In this case, it doesn't need to be specified because the default value of the Type property is String. If not specified, it is considered to have the value of String.
The RegularExpressionValidator server control is a validation control that enables you to check the user's input based on a pattern defined by a regular expression. This is a great control to check whether the user has entered a valid e-mail address or telephone number. In the past, these kinds of validations took a considerable amount of JavaScript coding. The RegularExpressionValidator control with ASP.NET saves coding time. In the Properties window for the RegularExpressionValidator server control, click the button in the ValidationExpression box, and Visual Studio.NET provides you with a short list of expressions to use in your form via the Regular Expression Editor. However, you are not limited to these regular expressions in your ASP.NET applications. The list of prepared expressions is shown in Figure 5.
Figure 5: The Regular Expression Editor For an example of using the RegularExpressionValidator server control to make sure that a value entered in a text box is an e-mail address, look at Listing 11. Listing 11: Validating an e-mail address
Email: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> <asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="You must enter an email address" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> </asp:RegularExpressionValidator>
In this example, notice that you place the Internet e-mail address regular expression in your ValidationExpression property. The great thing is that it is pretty simple, and it takes hardly any coding. Figure 6 shows the error message that results if a user enters an incorrect e-mail address in the text box.
Figure 6: Validating whether an e-mail address is entered in a text box Note The e-mail address is checked only to see whether it is in the correct format. The e-mail address is not checked in to ensure that it is an actual e-mail address. A great place on the Internet to find free regular expressions is the RegEx Library at RegExLib.com.
Email: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> <asp:RegularExpressionValidator id="RegularExpressionValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage='<img src="error.gif">' ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"> </asp:RegularExpressionValidator>
To use an image instead of text for your error messages, you use an HTML string that points to the image that you want to display for the value of the ErrorMessage property (see Figure 7).
Client-side Validation
One of the cool things about using the validation controls, in general, is that they allow for clientside validation of certain HTML server controls. As I said, you can create your own JavaScript functions that provide you with a higher level of validation capabilities. Listing 14 illustrates how to use JavaScript and the CustomValidator server control to expand upon the default validation capabilities that are provided to you with the .NET Framework. Listing 14: Creating your own client-side validation functions Visual C# .NET
<%@ Page Language="C#" %> <script runat="server"> void Button1_Click(Object sender, EventArgs e) { Label1.Text = "VALID NUMBER!"; } </script> <html>
<head> <script language="JavaScript"> function validateNumber(oSrc, args) { args.IsValid = (args.Value % 5 == 0); } </script> </head> <body> <form runat="server"> <p> Number: <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> <asp:CustomValidator id="CustomValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Number must be divisible by 5" ClientValidationFunction="validateNumber"> </asp:CustomValidator> </p> <p> <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button> </p> <p> <asp:Label id="Label1" runat="server"></asp:Label> </p> </form> </body> </html>
The important part of the CustomValidator server control here is the ClientValidationFunction property. The value of this property must be the client-side JavaScript function that is in the pagein this case, the validateNumber function. By simply using this with the ClientValidationFunction property, you have tied the validation process to the custom client-side function that you created, as illustrated in Figure 8.
Figure 8: Performing a custom client-side validation using the CustomValidator server control You set the args.IsValid property to either True or False in the JavaScript function. The args.Value property is the value from the user that is retrieved from the control that the CustomValidator server control is tied to. Using the ClientValidationFunction property enables you to incorporate your own JavaScript functions into ASP.NET controls so that they behave like the other validation controls.
Server-side Validation
The other way of performing validation on Web forms using the CustomValidator server control is to use server-side validation. This is just as easy as the client-side validation. Server-side validation of your Web forms enables you to create rather elaborate validation capabilities. Listing 15 shows you a not-too-elaborate example of server-side checking. Here the code determines whether the number entered in the text box on the ASP.NET page is even. Listing 15: Creating your own server-side validation functions Visual C# .NET
<%@ Page Language="C#" %> <script runat="server"> void Button1_Click(Object sender, EventArgs e) { if (Page.IsValid) { Label1.Text = "VALID ENTRY!"; } } void ValidateNumber(object source, ServerValidateEventArgs args) { try { int num = int.Parse(args.Value); args.IsValid = ((num%5) == 0); } catch(Exception ex) { args.IsValid = false; } } </script> <html> <head> </head> <body> <form runat="server"> <p> Number:
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox> <asp:CustomValidator id="CustomValidator1" runat="server" ControlToValidate="TextBox1" ErrorMessage="Number must be even" OnServerValidate="ValidateNumber"></asp:CustomValidator> </p> <p> <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button> </p> <p> <asp:Label id="Label1" runat="server"></asp:Label> </p> </form> </body> </html>
Performing custom server-side validation with the CustomValidator server controls requires that you use the OnServerValidate property instead of the ClientValidationFunction property. The ClientValidationFunction is used with the CustomValidator server control when working with client-side validation. In this case, you need to give the OnServerValidate property a value that is equal to the name of the server-side function that you would write in one of the .NET-compliant languages.
<%@ Page Language="C#" %> <script runat="server"> void CustomValidator1_ServerValidate(Object source, ServerValidateEventArgs args) {
void Button1_Click(Object sender, EventArgs e) { if (Page.IsValid) { Label1.Text = "Thank you for your donation!"; } else { Label1.Text = ""; } } </script> <html> <head> </head> <body> <form runat="server"> <p> Check checkbox if you want to donate $10 </p> <p> <asp:CheckBox id="CheckBox1" runat="server" Text="Donate $10"></asp:CheckBox> <asp:CustomValidator id="CustomValidator1" runat="server" ErrorMessage="Please donate $10" OnServerValidate="CustomValidator1_ServerValidate"> </asp:CustomValidator> </p> <p> <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Submit"></asp:Button> </p> <p> <asp:Label id="Label1" runat="server"></asp:Label> </p> </form> </body> </html>
Note that a CheckBox server control appears on the page. Also notice that there isn't a validation server control on the page that has this CheckBox server control tied to it via any property settings. Instead, a CustomValidator server control on the page references a server-side function called CustomValidator1_ServerValidate. Within this server-side function, validation performed in the code checks whether the CheckBox server control's Checked property has a value of True (meaning that it is checked). If the value of this property is True, the CustomValidator server control is passed a True valuemeaning that the input passed the test. The CustomValidator server control enables you to do almost any type of validations that you can think of. This is a great control to use if you do any database validations on the input that is
entered into a form by a user. This control can also apply any complicated logic that you want to include in the validation process.
<p>First name <asp:TextBox id="TextBox1" runat="server"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="You must enter your first name" ControlToValidate="TextBox1"></asp:RequiredFieldValidator> </p> <p>Last name <asp:TextBox id="TextBox2" runat="server"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="You must enter your last name" ControlToValidate="TextBox2"></asp:RequiredFieldValidator> </p> <p> <asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Submit"></asp:Button> </p> <p> <asp:ValidationSummary id="ValidationSummary1" runat="server" HeaderText="You received the following errors:"> </asp:ValidationSummary> </p> <p> <asp:Label id="Label1" runat="server"></asp:Label> </p>
Using this kind of construct, when the validation server control is triggered, error messages similar to the ones shown in Figure 9 appear on the screen.
Figure 9: Validation errors shown using the ValidationSummary server control By default, the ValidationSummary server control shows the errors in a bulleted list on the page using red text. You have the option to completely alter how output displays in the browser. To change how the error messages are displayed, you can change the value of the DisplayMode property of the ValidationSummary control. The possible values of this control can be set to the following:
If you use the BulletList value for the DisplayMode property, it appears as shown in Figure 11. If you use List, it appears without bullets. If you use SingleParagraph, the errors appear in a text area all on one line in a single paragraph.
ShowSummary property to False. To show validation errors in a dialog box, set the ValidationSummary control's ShowMessageBox property to True (see Listing 18).
Listing 18: Showing errors in a dialog box Copy
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
Or: Copy
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="You must enter your first name" ControlToValidate="TextBox1" Text="*"> </asp:RequiredFieldValidator>
By constructing the page's validation server controls, as shown here, using different values for the ErrorMessage and Text properties, you get a result similar to that shown in Figure 11.
Figure 11: Using different text for the validation error messages When both the ErrorMessage and Text properties are used for the validation controls, the value of the ErrorMessage property is displayed in the ValidationSummary server control's listing of validation errors, and the value assigned to the Text property is displayed in the validation control itself.