Manipulating data 39 in asp.net 2.0: Adding validation controls to the DataList editing interface-self-study process

Source: Internet
Author: User
Tags eval exception handling

Introduction

So far the discussion in the DataList tutorial does not include any validation user input, even if the user is illegally typing-missing product name or negative price-can cause an exception. In the previous chapter we learned how to add exception handling code in DataList UpdateCommand event handling to catch it when an exception occurs and display friendly error messages. However, the ideal editing interface should contain validation controls to prevent users from entering some illegal data in the first time.

In this chapter we will learn to add validation controls to the DataList EditItemTemplate to provide a more secure editing interface, which is very easy. This chapter uses the example that you created earlier and expands the editing interface to add the appropriate validation controls.

The first step: from processing BLL and DAL to the exception copy example

In handling the BLL and DAL exceptions, we created a two-column listing of product name and price DataList. The goal of this chapter is to extend this DataList editing interface so that it contains validation controls. Our validation logic is as follows:

The name of product is required
Make sure that the value of price entered is a valid currency type format
Make sure the value of price entered is greater than or equal to 0

We first need to copy the Errorhandling.aspx page example into the uivalidation.aspx. This includes the page's declaration code and the background code. Here is the procedure for replicating the Declaration code:

In Visual Studio's Open errorhandling.aspx switch to Source view to copy the code from the <asp:Content> to </asp:Content> tab, see Figure 1.


Figure 1: Copying the code within <asp:Content>

Open uivalidation.aspx Switch to Source view and paste the code.

After you complete the steps above, open ErrorHandling.asxp.cs, copy the Dispalyexcetiondetails method, and three event handling (Products_editcommand,products_cancelcommand , and Products_updatecommand), be careful not to copy the code that declares the class and the using. Paste the code into the Editdeletedatalist_uivalidation class in ErrorHandling.asxp.cs. After you have done this, browse the page. Both of these pages are the same for both output and functionality (see Figure 2).


Figure 2:uivalidation.aspx Page errorhandling.aspx same

Step two: Add validation controls for the DataList EditItemTemplate

When creating an input table, it is important to declare that required fields and user input must be well-formed legal values. To ensure that user input is legal, ASP. NET provides 5 built-in validation controls that are designed to validate input values in a single input control.

requiredfieldvalidator-ensure required values
comparevalidator-verify a value based on the value or constant of another control, or make sure that the input value is a specific type
rangevalidator-ensure that the input value is within a range
regularexpressionvalidator-to validate a value based on the regular expression (regular expression)
customvalidator-to validate a value based on user-defined methods

For more information on these 5 controls, refer to adding validation controls to the edit and add interface or to the validation Controls section in asp.net Quickstart tutorials.

In this chapter we need to use RequiredFieldValidator to ensure that the user enters the name,comparevalidator of the product to ensure that the value of price is greater than or equal to 0 and is in the legal currency format.

  Note: These validation controls are already included in the ASP.net 1.x, and there are many improvements in asp.net 2.0. One of the most important 2.1 is client script support for browsers other than IE, and the second is grouping of validation controls on the same page. For more than 2.0 years, please refer to dissecting the Validation Controls in asp.net 2.0 for information on new features of validation controls.

Now we're going to add the validation controls that we need to the DataList EditItemTemplate. This can be done by clicking on the edit Template on the DataList smart Tag, or by writing a declaration code directly. We use the first method here. After selecting Edit Template drag a RequiredFieldValidator in and place it behind the ProductName textbox.


Figure 3: Adding RequiredFieldValidator

All validation controls validate only a single Web control. So we need to indicate that the RequiredFieldValidator we just added is used to validate the ProductName TextBox. This association is done by setting the ControlToValidate property of the validation control to the appropriate Web control (here is ProductName). Then set the ErrorMessage property to "You must provide the Product ' s name ', the Text property is set to ' * '. If the value of the Text property is provided, it will be displayed when the validation fails. The ErrorMessage property is provided for use by the ValidationSummary control. If the value of text is omitted, errormessage is displayed when illegal input. After completing these, your page should look similar to Figure 4:


Figure 4: Setting the RequiredFieldValidator controltovalidate, errormessage, and text Properties

After adding RequiredFieldValidator, the rest is to add validation controls for the price of product. Because UnitPrice are optional when editing, we don't need to add RequiredFieldValidator. What we need to do is add a comparevalidator to ensure that when Price is entered, its value is in the correct currency format and is greater than or equal to 0.

Add a ControlToValidate property to the edititetemplate for the UnitPrice CompareValidator. Set ErrorMessage as "The price must is greater than or equal to zero and cannot include the currency symbol", and the text is set to "*". To specify that the value of the UnitPrice must be greater than or equal to 0, set the CompareValidator operator property to the Greaterthanequal,valuetocompare property set to "0", Type property is set to currency. After you add the two validation controls, the DataList EditItemTemplate declaration code should be similar to the following:

<EditItemTemplate> Product Name: <asp:textbox id= "ProductName" runat= "Server" text= "<%#" Eval ("ProductName ")%> ' ></asp:TextBox> <asp:requiredfieldvalidator id=" RequiredFieldValidator1 "controltovalidate=" ProductName "errormessage=" You must provide the product ' s name ' runat= ' server ' >*</asp:requiredfieldvalidator&gt
 ; <br/> Price: <asp:textbox id= "UnitPrice" runat= "server" text= ' <%# "Eval (" UnitPrice "," {0:c} ")%> ' &GT;&L t;/asp:textbox> <asp:comparevalidator id= "CompareValidator1" controltovalidate= "UnitPrice" "errormessage=" the Price must is greater than or equal to zero and cannot include the currency symbol ' operator= ' greaterthanequal ' Type = "Currency" valuetocompare= "0" runat= "server" >*</asp:comparevalidator><br/> <br/> <asp: Button id= "updateproduct" runat= "Server" commandname= "Update" text= "Update"/> <asp:button "id=" Run at= "Server" commandname= "Cancel" Text= "Cancel"/> </EditItemTemplate>
 

Browse the page. Now if you edit without entering name or entering an illegal value in price, a "*" appears behind the TextBox. See Figure 5. A value that contains a currency symbol-for example, $19.95-is considered legal. The CompareValidator currency type allows numeric delimiters (such as periods and commas) and preceded with a "+" or "-" sign, but no currency symbol is allowed. The UnitPrice in the editing interface will also be displayed in currency format, which may confuse users.


Figure 5: The "*" appears after the illegal input textboxes

It is not acceptable for a user to manually remove the currency symbol while editing, when the validation control works like this. Also, if there is an illegal input at the time of editing, the page will be postback, whether it is click Update or Cancel button. Ideally, the Click Cancel button returns the DataList state of the editor, regardless of whether the value entered is legitimate. Of course, since the user's browser may not support JavaScript or is disabled, we need to make sure that the page's data is legitimate before updating the product information in UpdateCommand event processing.

To remove the currency symbol from the EditItemTemplate unitprice textbox

When you use the CompareValidator currency type, the input cannot contain any currency symbols, otherwise comparevalidator is considered illegal. However, the UnitPrice textbox in the editing interface already contains a currency symbol, which means that the user must manually remove it before saving. We have three ways to fix it:

Configure EditItemTemplate The value of the UnitPrice TextBox is not formatted as currency. Use RegularExpressionValidator instead of CompareValidator to check for currency values in the correct format. The challenge here is to use regular expressions that are not as straightforward and convenient as comparevalidator, and need to write some code. Remove all validation controls, and the validated functionality will depend entirely on the RowUpdating event handling of the server-side gridview.

We use the first method here. The UnitPrice is now in currency format due to the binding expression of the TextBox <%# Eval ("UnitPrice", "{0:c}")%>. Modify it to Eval ("UnitPrice", "{0:n2}") (a number that allows two decimal digits). This can be done by clicking the Edit DataBindings link in the UnitPrice textbox in the DataList EditItemTemplate or by directly modifying the declarative syntax. When this is done, the price format of the editing interface contains two delimiters, commas, and periods.

  Note: When I remove the currency format, I find it a good practice to place the currency symbol in front of the textbox as text. It will remind users that they do not need to enter the currency symbol again.

Repair Cancel Button

By default, the validation control generates JavaScript to perform validation on the client. When you click the button, LinkButton, or ImageButton, the validation control checks before the page postback. If there are illegal data, postback will not happen. However, for some button, there is no need to validate the data. In such cases, the cancellation of the postback is very annoying.

This is the case with the Cancel button. Imagine that the user has entered illegal data, such as ignoring the name of product, and then deciding that he does not need to save the product and then clicking the Cancel button. In this case, the Cancel button triggers the validation control, which reports that the name of the product is missing and blocks the postback. Our users have to enter some text into the product textbox and then cancel the edit.

Fortunately, Button, LinkButton, and ImageButton have CausesValidation property, which can indicate whether validation is required when clicking the button (the default is true). Set the causesvalidation of the Cancel button to False.

Make sure the input is legal in the UpdateCommand Event handler

The client's script is generated by the validation control and will not cause postback if the user enters illegal data and clicks the button with the CausesValidation property to True. However, if a user user is using a low version browser or has disabled support for JavaScript, the client's validation will not be performed.

When the page postback, all validation controls perform validation and then submit the validation report to the Page.IsValid property. However, the entire process is not interrupted by page.isvalid values. As a developer, we need to ensure that the code continues to run if Page.IsValid is true.

If JavaScript-disabled users Browse our pages, edit the product, enter a "too expensive" value in price, then click the Update button, the client's validation will be skipped and the page will continue to postback. UpdateCommand event processing executes, and then throws an exception when an attempt is made to convert a "too expensive" price to decimal. Although exception handling has been written, we can actually block illegal input at the first time based on the value of Page.IsValid.

Add the following code at the beginning of the UpdateCommand:

if (! Page.IsValid) return
 ;

Once this is done, the product will be updated only when the data submitted is legitimate. Illegal submissions by most users are rejected because of client script, and customers who do not support JavaScript or postback JavaScript will skip client checks and submit illegal data.

Note: Careful readers will remember that when updating data in the GridView, we do not need an explicit check of Page.IsValid. This is because the GridView has helped us complete this part of the work, that is, it will continue to update only when Page.IsValid is true.

Step three: Summarizing Data Entry Problems

In addition to the 5 types of validation controls mentioned above, ASP. NET also contains ValidationSummary control, which is used to display error messages for validation controls that check for illegal data. These summarized data can be displayed as text or as a client message box. We will now add a client message box that contains the validation problem rollup information.

Drag a ValidationSummary in. Because we configured it to display summary information as a message box, it doesn't matter where it is. Set the ShowSummary property to False and the ShowMessageBox property to True. This way, all validation error messages are displayed in the form of a client message box. See Figure 6.


Figure 6: Error message summarizing validation with a client message box

Summarize

In this chapter we learned how to use validation controls to ensure that user input is legitimate before the update starts, thereby reducing the appearance of exceptions. Asp. NET provides 5 validation controls to check the input of a particular control and report whether it is legitimate. In this chapter we use two of these-requiredfieldvalidator and comparevalidator-to ensure that product name is mandatory and that price is a currency format that is greater than or equal to 0.

The validation controls in the DataList editing interface simply drag them into the EditItemTemplate and set several properties. By default, validation controls generate client-side validation scripts automatically, and, of course, provide server-end validation at postback and accumulate all results in page.isvalid. When you click Button,linkbutton or ImageButton, you can set the CausesValidation to False to skip client validation. Before executing any code, you first need to ensure that page.isvalid is true.

The DataList editing tutorials we've been learning at the moment are simply interfaces-displaying name and price in a textbox. However, the editing interface can contain various Web controls, such as Dropdownlists,calenda,radiobuttons, checkboxes, and so on. Our next chapter creates an interface that contains a variety of Web controls.

I wish you a happy programming!

Introduction of the author

Scott Mitchell, author of this series of tutorials, has six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. You can click to see all Tutorials "[translation]scott Mitchell asp.net 2.0 data tutorial," I hope to learn asp.net help.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.