asp+ input Check (e-text, turn)

Source: Internet
Author: User
Tags date definition comparison final html page object model sort valid
asp+ Source Http://msdn.microsoft.com/library/default.asp?URL=/library/techart/PDC_userinput.htm Introduction
Validating user input is a common scenario in a web-based application. For production applications, the developers often end up spending a lot the more time and code on this task than we are like. In building the asp+ page framework, it is important to try and make the task of validating input a lot easer than it has been in the past. The Problem
In HTML 3.2, validating the data is a difficult process. Need to write code to check the input and write any errors the user has made the Page to help the user to correctly fill in the validation form. This is a taxing process for end users, developers, and servers alike.
Dthml and scripting languages improve things somewhat. It is possible to provide the user with immediate feedback on bad input and to prevent them from posting a page until it h As been corrected. However, it can be almost impossible to guarantee that every user of your site has the required scripting. This usually means so if you are want to the interface of your pages, and you are have to write the same valid ation logic twice, once on the client, and again on the server, just in the client code cannot is executed. The objective
Our objective with validation is as follows:
    • Provide components can perform percent or more of the typical input validation tasks for data entry pages.

    • Have These components perform rich script-based validation on modern browsers This can also effectively fall back to pure HTML 3.2 server-based validation, if required.

    • Provide a flexible API so, any validation tasks does not covered by the components easy to are.

We visited a large number of real pages to determine this sort of scenarios these components needed to is able to handle. We wanted to dramatically reduce the amount of validation code needed for future applications. The Solution-overview
The validator controls are the main elements of the solution. A validator is a visual asp+ control that checks a specific validity condition of another. It generally appears to the user as a piece of text this displays or hides depending on whether the control it is checking is in error. It can also be a image, or can even be invisible and still do useful work. There are five types of validator controls that perform different types of checks.
Another element in our solution are the ValidationSummary control. Large data Entry pages generally have a area where all errors are. The ValidationSummary automatically generates this content is gathering it up from validator to on the page.
The final element is the Page object itself. It exposes the all-important "IsValid" property, which your check in server code to determine if all of the user input is O K. Client Features
Most Web sites do all of their validation checks on the server. You are need to write the server-based checks anyway for clients script and so it can is without to hard justify it all O Ver again for rich clients.
Validation controls change all this, because almost all of the duplicated logic is encapsulated in the controls. If a client with Internet Explorer 4.0 or later uses your page, it can does the same input validation that takes place on th E server without you have to write any special client script.
The client side validation has a number of features:
    • Errors can appear and disappear immediately after the ' bad ' input is entered/corrected. This immediate feedback makes it very easier to correct bad input.

    • Post-back is prevented if there are errors this are detectable on the client, saving the user time and reduces the Server.

    • The ValidationSummary updates itself without posting back if it detects errors.

    • The ValidationSummary can optionally display a message box to the user if there are errors.

    • The client logic is all contained in a JScript library, so no ActiveX components or Java applets are used.

    • Can Optionally use VBScript to perform checks involving localized date and number comparison.

    • An object model is exposed on the client to allow enhancement of client-side validation and behavior.
What is a Validator?
In order to use validators effectively, it helps to have a firm definition of what they. Let ' s refine our previous definition a little:
"A validator is-a control"-checks one input control for a specific type of error condition and displays a description Of that problem. "
This is a important definition, because it means that your frequently need to use more than one validator Input control.
For example, if your want to check whether or not user input in a-text box is (a) nonblank, (b) a valid date between a part Icular range and (c) less than the date in another text input control, for would want to use three. While this might seem cumbersome, remember which is helpful to the user, and you would want to have three different text des Criptions for all these cases.
The different types of validators are listed as follows:requiredfieldvalidatorchecks that the user has entered or selected anything. Regularexpressionvalidatorchecks user input against a regular expression. This allows a wide variety of the checks to be made and can is used for things like ZIP codes and phone numbers. Comparevalidatorcompares an input control to a fixed value or another input control. It can be used to password verification fields for example. It is also possible to do typed date and number comparisons. Rangevalidatormuch like CompareValidator, but can check that the input is between two values or the values of other input Controls. Customvalidatorthis allows you to write your own the code to take part in the validation framework.
Validator Walk-through
To demonstrate validation, we'll walk through the process of adding validation to a existing page. Here are some example requirements:
Write a Web page to collect a new user ID and password. The user ID must contain 6-10 alpha characters and must not already do. The password must contain 4-12 letters, at least one and at least one of the characters "@#$%^&*/". The user must re-enter the password to make sure they entered it correctly.
I am going to start with a HTML page that has been minimally converted to work with the asp+ page framework.
The process of converting the page includes the following steps:
    1. Change the extension from ". html" or ". asp" to ". aspx.

    2. The change of the form and all of the input tags to is "runat=server".

    3. Use "ID" instead of "name".

Starting code:


Starting Page:
It ' s not voluntary
The the thing we need to enforce are that the fields get filled in all.
In front of each field, we add a RequiredFieldValidator. If The input field is blank, we are want to display a asterisk (*) in front of the field and a-text error in a summary Area. Here are how do we add a RequiredFieldValidator to the User ID field:
<tr> <td> <asp:requiredfieldvalidator runat=server controltovalidate=txtname Errormessage= "User ID is required." > * </asp:RequiredFieldValidator> </td> <td>user id:</td> <td><input t Ype=text Runat=server id=txtname></td> </tr>

The * is displayed next to the label if the input is blank. The error message was reported in a summary. The "ControlToValidate" property specifies the ID of the control to validate. The final step are to add a validation summary to the "the" page like so:
<asp:validationsummary runat=server headertext= "There were errors on the page:"/>

Here are how it looks on the page:
getting Regular
Next we need to enforce the character requirements for the User ID and Password fields. For these we'll use RegularExpressionValidator controls. Regular expressions can is very powerful in concisely expressing the for this sort of checks, as as as a ZIP information , phone numbers, and e-mail addresses.
Here are how we specify the restrictions on User ID:
<td> <input type=text runat=server id=txtname> <asp:regularexpressionvalidator runat=server             Controltovalidate= "Txtname" errormesage= "ID must be 6-10 letters." Validationexpression= "[a-za-z]{6,10}"/> </td>

Note "In" We did not specify any inner content within the tag. The inner text is equivalent to the "text" of the control. If It is blank, it's error message would be displayed where the control is positioned, as the as-as-appearing in the summary.
The password checks can be done with the following two validators. If you have more than one, they must all match before the ' input is considered valid.
<asp:regularexpressionvalidator runat=server display=dynamic controltovalidate= "TxtPWord" ErrorM            Essage= "Password must contain one of @#$%^&*/."            Validationexpression= ". *[@#$%^&*/].*"/> <asp:regularexpressionvalidator runat=server display=dynamic             Controltovalidate= "Txtpword" errormessage= "Password must be 4-12 nonblank." Validationexpression= "[\s{4,12}"/>]

This is the "form in action" with the expressions:
comparing Apples and Apples
We need to make sure the password re-entry field matches the password. We'll use the ' CompareValidator to do ' this, since it's capable of working with two input controls in a time:
<asp:comparevalidator Runat=server Controltovalidate=txtrepword Controltocompare=txtpword Errormessage= "passwords does not match."/>

By default, CompareValidator does a simple string match comparison. If required, it can do more complex comparisons involving dates and numbers. Custom Fit
The final thing we need to check is this the name is not already taken at our hypothetical site. This is going to require looking in some data on the server. To simulate this, I'll create a dummy function in Server-side code that checks that the "the" "A" T He following Visual Basic function was defined on the page:
Public Function Checkid (source as Object, value as String) as Boolean return value.substring (0, 1). ToLower () <> " A "End Function

To the call this function, I'll add a CustomValidator, which is designed to call developer the code to perform its check. This is the declaration:
<asp:customvalidator runat=server controltovalidate= "txtname" errormessage= "ID is already in use             ." onservervalidationfunction= "Checkid"/>

This is the can also call custom functions in client script, and although that would not being practical if this really had value in a database. On a-client with script, all of the other validators does their checks on the client-I-before allowing the submit to take P Lace. If There are errors detected by Server-only as this one, page would be checks the back to the user sent indicating Rs. The finale
Now, the ' only thing ' to ' to ' is ' nicely validated data. All need to do are check the IsValid property of Page to work out if you can proceed to update your database. Here are how to your submit handler might look:
Public Sub OnSubmit (source as Object, E as EventArgs) if Page.IsValid then ' now we can perform our transaction. End IfEnd Sub

As you can, this handler'll allow your data entry pages to consist of code which is specific to your application EAD of being full of code to deal with mundane input checking.
This is some to the final page in action:



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.