16.6 Validating Input Data and Displaying Errors

 <  Day Day Up  >  

You want to perform validation on a form and display an error if validation fails for certain fields.


Technique

A validator within the .NET Framework works to notify a user that a value within a control in a Web Form is invalid and must be changed before the form can be submitted successfully. You can apply five possible validators to controls on a Web Form.

The RequiredFieldValidator causes validation to fail if the user leaves the value of a control blank. To create a RequiredFieldValidator , drag the RequiredFieldValidator control from the toolbox and drop it next to the control to validate. Next , change the Text and ErrorMessage properties that appear when validation fails. You can optionally create a ValidationSummary control, which lists all error messages for controls that have failed validation. If you use a summary, the ErrorMessage property appears in the summary, and the Text property appears at the location of the validation control:

 
 <asp:ValidationSummary id="ValidationSummary1" runat="server"   Width="619px" HeaderText="The following errors occurred."/> 

Finally, change the ControlToValidate property of the RequiredFieldValidator by selecting the Web Form control that you are validating. The following example creates a TextBox control that displays an error message from a RequiredFieldValidator control if the TextBox is left blank:

 
 <asp:TextBox id="tbName" runat="server" Width="392"></asp:TextBox> <asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage=   "Name is required" ControlToValidate="tbName">*</asp:RequiredFieldValidator> 

Another validation control you can use is the RangeValidator . This validator checks the value of the input field and determines whether it falls within a specific range of values. Creating a RangeValidator follows the same method as the RequiredFieldValidator . After you drag and drop the validator and set the ErrorMessage , Text , and ControlToValidate properties, you can set the range of possible values. The MinimumValue and MaximumValue values denote the range of possible values the input field can have. However, this range of values does not automatically assume that the values are integers. To create an integer range, change the Type property to Integer . Other possible types include double , currency , date , and string values. The RangeValidator converts the input field to the type specified in the Type property before making the range check. The following example uses a TextBox with a valid range of values from 1 to 100:

 
 <asp:textbox id="tbNumber" runat="server" Width="392px"></asp:textbox> <asp:rangevalidator id="RangeValidator1" runat="server"  ErrorMessage="Number must be between 1 and 100" ControlToValidate="tbNumber" MinimumValue="1" MaximumValue="100"  Type="Integer">*</asp:rangevalidator> 

The CompareValidator performs a comparison on the values of two controls. It too contains ErrorMessage , Text , and ControlToValidate properties as do the other validator controls. To compare the control being validated against the value of another control, set the ControlToCompare property. Just like the RangeValidator , the CompareValidator converts the values of each control to a specified type before performing the comparison. To control the type conversion, change the Type property of the validator. Finally, you use the Operator property to control the logical operation to perform. For instance, to compare the control values to see whether they are equal, set the Operator property to Equal . Other possible values include NotEqual , GreaterThan , and GreaterThanEqual to name a few. The following example shows two TextBox controls with a CompareValidator attached to the tbConfirmPassword control. Whenever the user submits the form, a comparison happens to ensure that the confirmation password is equal to the password entered in the first TextBox :

 
 <asp:textbox id="tbPassword" runat="server" Width="392px"  TextMode="Password"></asp:textbox> <asp:textbox id="tbConfirm" runat="server" Width="392px"  TextMode="Password"></asp:textbox> <asp:comparevalidator id="CompareValidator1" runat="server"     ErrorMessage="Confirmation password does not match Password field"     ControlToValidate="tbConfirm" Display="Dynamic"     ControlToCompare="tbPassword">* </asp:comparevalidator> 

The RegularExpressionValidator matches the input field of the control with a regular expression that you supply. In addition to the normal error message strings and the ControlToValidate properties that are present on all validator controls, set the ValidationExpression property to a string representing the regular expression. To validate a phone number contained within a TextBox , attach a RegularExpressionValidator , as shown in the following code:

 
 <asp:textbox id="tbPhone" runat="server" Width="392px"></asp:textbox> <asp:regularexpressionvalidator id="RegularExpressionValidator1" runat="server"     ErrorMessage="Phone number must be in the form XXX-XXX-XXXX"     ControlToValidate="tbPhone" ValidationExpression="^\d{3}-\d{3}-\d{4}$">* </asp:regularexpressionvalidator> 

Sometimes, none of the validation controls are sufficient to perform validation on a control. For these cases, you can use a CustomValidator control. The only properties to set for this validation control are the ErrorMessage , Text , and ControlToValidate properties, just as you do with the other validation controls. To validate the control, create an event handler for the ServerValidate event. The second parameter for the event handler is a ServerValidateEventArgs object that contains a property named Value which contains the value of the control being validated. To specify that the control value is invalid, set the IsValid property defined in the event arguments object to false , which causes the validation to fail and a subsequent error message to display. For instance, to validate a TextBox value against a list of colors, the code would look like Listing 16.3.

Listing 16.3 Validating a TextBox Control
 private void ColorValidator_ServerValidate(object source,     System.Web.UI.WebControls.ServerValidateEventArgs args) {     string[] colorArray = new string[]{"red", "orange", "yellow",         "green", "blue", "indigo", "violet"};     ArrayList colorList = new ArrayList( colorArray );     if( colorList.Contains( args.Value.ToLower() ))     {         args.IsValid = true;     }     else     {         args.IsValid = false;     } } 

Comments

The first time we saw .NET in action was at a developer conference. Two things stood out as truly remarkable . The first was the Anchor property for Windows Forms, and the other was form validation within ASP.NET. If you've ever had to write dynamically resizing control code or validate input fields for an HTML form, then you'll probably agree.

As mentioned earlier, the .NET Framework contains five controls that allow you to seamlessly add form validation to your Web application. In the examples shown earlier for each of the validation controls, it was assumed that a ValidationSummary control accompanied the page. This ValidationSummary extracts the ErrorMessage field of each control that fails validation and places those messages within a HTML list. Once you add a ValidationSummary control to a form, the semantics of each validation control change with respect to the ErrorMessage and Text properties. The ErrorMessage appears in the ValidationSummary , and the Text value appears within the validation control. If either property value is blank, then the remaining value is used in both places. If instead there is no ValidationSummary , the validation control first checks the Text property and uses it. If the Text property is an empty string, then the ErrorMessage property is used.

One thing you have to watch when using validators is the possibility of empty fields within the form. If a user leaves a field blank and that field uses a validator, the field actually passes validation. In other words, if a RangeValidator validates the value in a TextBox and the user leaves that TextBox blank, the validation actually passes and no error message appears. To fix this problem, create a RequiredFieldValidator to prevent the user from leaving the field blank.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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