aspinput validation control

Upload: bonny-mavyks

Post on 09-Apr-2018

223 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/8/2019 ASPInput Validation Control

    1/57

    ASP.NET Technical ArticlesUser Input Validation in ASP.NET

    Anthony Moore

    Microsoft Corporation

    July 2000Updated March 2002

    Summary: Provides a brief overview of the validation framework in ASP.NET and walksthrough an example of adding validation to a page. (11 printed pages)

    Contents:

    Introduction

    The ProblemThe ObjectiveThe Solution-OverviewClient FeaturesWhat Is a Validator?Validator Walk-ThroughIt's Not VoluntaryGetting RegularComparing Apples and ApplesCustom FitThe Finale

    Sample Code

    Introduction

    Validating user input is a common scenario in a Web-based application. For productionapplications, developers often end up spending a lot more time and code on this task than wewould like. In building the ASP.NET page framework, it was important to try and make the taskof validating input a lot easer than it has been in the past.

    The Problem

    In HTML 3.2, validating data is a difficult process. Each time you get a request, you need towrite code to check the input and write any errors the user has made back to the page to help theuser to correctly fill in the form. This is a taxing process for end users, developers, and serversalike.

    DTHML and scripting languages improve things somewhat. It is possible to provide the userwith immediate feedback on bad input and to prevent them from posting a page until it has been

    http://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputintrohttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputprobhttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputobjhttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputoverhttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputfeathttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputvalidhttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputwalkhttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputnothttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputreghttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputappleshttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputfithttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputfinalehttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputsamplecodehttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputprobhttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputobjhttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputoverhttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputfeathttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputvalidhttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputwalkhttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputnothttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputreghttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputappleshttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputfithttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputfinalehttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputsamplecodehttp://msdn.microsoft.com/en-us/library/ms972961.aspx#pdc_userinputintro
  • 8/8/2019 ASPInput Validation Control

    2/57

    corrected. However, it can be almost impossible to guarantee that every user of your site has therequired scripting environment. This usually means that if you want to use script to improve theinterface of your pages, you have to write the same validation logic twice, once on the client, andagain on the server, just in case the client script cannot be executed.

    The Objective

    Our objective with validation is as follows:

    Provide components that can perform 90 percent or more of the typical input validationtasks for data entry pages.

    Have these components perform rich script-based validation on modern browsers that canalso effectively fall back to pure HTML 3.2 server-based validation, if required.

    Provide a flexible API so that any validation tasks not covered by the components areeasy to complete.

    We visited a large number of real pages to determine the sort of scenarios these componentsneeded to be able to handle. We wanted to dramatically reduce the amount of validation codeneeded for future applications.

    The SolutionOverview

    The validator controls are the main elements of the solution. A validator is a visual ASP.NETcontrol that checks a specific validity condition of another control. It generally appears to theuser as a piece of text that displays or hides depending on whether the control it is checking is inerror. It can also be an 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 is the ValidationSummary control. Large data entry pagesgenerally have an area where all errors are listed. The ValidationSummary automaticallygenerates this content by gathering it up from validator controls on the page.

    The final element is the Page object itself. It exposes the all-important "IsValid" property, whichyou check in server code to determine if all of the user input is OK.

    Client Features

    Most Web sites do all of their validation checks on the server. You need to write the server-basedchecks anyway for clients without script, so it can be hard to justify writing it all over again forrich clients.

    Validation controls change all that, because almost all the duplicated logic is encapsulated in thecontrols. If a client with Internet Explorer 4.0 or later uses your page, it can do the same inputvalidation that takes place on the server without you having to write any special client script.

  • 8/8/2019 ASPInput Validation Control

    3/57

    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 much easier to correct bad input.

    Post-back is prevented if there are errors that are detectable on the client, saving the user

    time and reducing hits on 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. 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 are. Let'srefine our previous definition a little:

    "A validator is a control that checks one input control for a specific type of error condition anddisplays a description of that problem."

    This is an important definition, because it means that you frequently need to use more than onevalidator control for each input control.

    For example, if you want to check whether or not user input in a text box is (a) nonblank, (b) avalid date between a particular range and (c) less than the date in another text input control, you

    would want to use three validators. While this might seem cumbersome, remember that to behelpful to the user, you would want to have three different text descriptions for all these cases.

    The different types of validators are listed as follows:

    RequiredFieldValidator Checks that the user has entered or selected anything.

    RegularExpressionValidatorChecks user input against a regular expression. This allows a widevariety of checks to be made and can be used for things like ZIPcodes and phone numbers.

    CompareValidatorCompares an input control to a fixed value or another input control.It can be used for password verification fields, for example. It is alsopossible to do typed date and number comparisons.

    RangeValidatorMuch like CompareValidator, but can check that the input isbetween two fixed values.

    CustomValidatorThis allows you to write your own code to take part in the validationframework.

    Validator Walk-Through

  • 8/8/2019 ASPInput Validation Control

    4/57

    To demonstrate validation, we will walk through the process of adding validation to an existingpage. Here are some example requirements:

    Write a web page to collect a new user id and password. The user id must contain 6-10 alphacharacters and must not already be in use. The password must contain 4-12 letters and at least

    one of the characters "@#$%^&*/." The user must re-enter the password to make sure theyentered it correctly.

    I am going to start with an HTML page that has been minimally converted to work with theASP+ page framework.

    The process of converting the page includes the following steps:

    1. Change the extension from ".html" or ".asp" to ".aspx".2. Change the form and all the input tags to be "runat=server".3. Use "ID" instead of "name".

    Starting code:

    Validation Sample

    Please enter a new User ID and Password:

    User ID:Password:

    Re-enter Password:


    Starting page:

  • 8/8/2019 ASPInput Validation Control

    5/57

    It's Not Voluntary

    The first thing we need to enforce is that the fields get filled in at all.

    In front of each field, we add a RequiredFieldValidator. If the input field is blank, we want todisplay an asterisk (*) in front of the field and report a text error in a summary area. Here is howwe add a RequiredFieldValidator to the User ID field:

    *

    User ID:

    The * is displayed next to the label if the input is blank. The error message is reported in asummary. The "ControlToValidate" property specifies the ID of the control to validate. The finalstep is to add a validation summary to the top of the page like so:

    Here is how it looks on the page:

  • 8/8/2019 ASPInput Validation Control

    6/57

    Getting Regular

    Next we need to enforce the character requirements for the User ID and Password fields. Forthese we will use RegularExpressionValidator controls. Regular expressions can be verypowerful in concisely expressing checks for this sort of information, as well as ZIP codes, phonenumbers, and e-mail addresses.

    Here is how we specify the restrictions on User ID:

    Note that in this case we did not specify any inner content within the tag. The inner text isequivalent to the Text property of the control. If it is blank, the error message will be displayedwhere the control is positioned, as well as appearing in the summary.

    The password checks can be done with the following two validators. If you use more than one,they must all match before the input is considered valid.

  • 8/8/2019 ASPInput Validation Control

    7/57

    ValidationExpression="[^\s]{4,12}" />

    Here 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 will use theCompareValidator to do this, since it is capable of working with two input controls at a time:

    By default, CompareValidator does a simple string match comparison. If required, it can do morecomplex comparisons involving dates and numbers.

    Custom Fit

    The final thing we need to check is that the name is not already taken in our hypothetical site.This is going to require looking at some data on the server. To simulate this, I will create adummy function in server-side code that checks that the first character is not an "a." Thefollowing Visual Basic function is defined on the page:

    public sub CheckID(source as Object, args as ServerValidateEventArgs)args.IsValid = args.Value.substring(0, 1).tolower() "a"

    end sub

  • 8/8/2019 ASPInput Validation Control

    8/57

    To call this function, I will add a CustomValidator, which is designed to call developer code toperform its check. Here is the declaration:

    On a client with script, all the other validators do their checks on the client first before allowingthe submit to take place. If there are errors detected by server-only checks like this one, page willbe sent back to the user indicating those errors.

    The Finale

    Now, the only thing left is to make use of the nicely validated data. All you need to do is checkthe IsValid property of Page to work out if you can proceed to update your database. Here is howyour submit handler might look:

    public sub OnSubmit(source as Object, e as EventArgs)if Page.IsValid then

    ' Now we can perform our transaction.end if

    end sub

    As you can see, this handler will allow your data entry pages to consist of code that is specific toyour application instead of being full of code to deal with mundane input checking.

    Here is some more of the final page in action:

    Sample Code

  • 8/8/2019 ASPInput Validation Control

    9/57

    public sub CheckID(source as Object, args as ServerValidateEventArgs)args.IsValid = args.Value.substring(0, 1).tolower() "a"

    end sub

    public sub OnSubmit(source as Object, e as EventArgs)if Page.IsValid then

    ' Now we can perform our transaction.end if

    end sub

    Validation Sample

    Please enter a User ID and Password:

    *

    User ID:

    *

    Password:

  • 8/8/2019 ASPInput Validation Control

    10/57

    *

    Re-enter Password:


    Microsoft Corporation. All rights reserved.

    ASP.NET Technical Articles

    Validating ASP.NET Server Controls

    By Bill EvjenReuters

    http://msdn.microsoft.com/en-us/library/ms369863.aspxhttp://reuters.com/http://msdn.microsoft.com/en-us/library/ms369863.aspxhttp://reuters.com/
  • 8/8/2019 ASPInput Validation Control

    11/57

    December 2003

    Applies to:Microsoft ASP.NETMicrosoft Visual Basic .NET

    Microsoft Visual C# .NET

    Summary: Learn how to use all the available ASP.NET validation server controls that are atyour disposal. This paper introduces these new controls and discusses tips and tricks on workingwith them in practical scenarios. (34 printed pages)

    IntroductionLooking at ValidationThe RequiredFieldValidator ControlThe CompareValidator ControlThe RangeValidator Control

    The RegularExpressionValidator ControlThe CustomValidator ControlThe ValidationSummary ControlConclusion

    Introduction

    In your studies of ASP.NET, you might have been introduced to a number of different types ofcontrols, whether HTML server controls or Web server controls. This paper focuses on a seriesof controls that stand out from the restvalidation server controls.

    Validation server controls are a series of controls that help you validate the data that the userenters into the other controls that are provided with ASP.NET. They determine whether the formcan 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 thatis posted back to the server. These forms are made up of different types of HTML elements thatare constructed using straight HTML, HTML server controls, or Web server controls. A varietyof 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 toensure that the data that you collect is valid. Some users are not interested in spending enoughtime to enter the correct information into a form, and in some cases, users might evenintentionally enter false information to gain access or get past a certain step in your application'sworkflow process.

    http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic1http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic2http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic3http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic4http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic5http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic6http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic7http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic8http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic9http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic1http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic2http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic3http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic4http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic5http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic6http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic7http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic8http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic9
  • 8/8/2019 ASPInput Validation Control

    12/57

    One of the first steps is to understand what validating data means. Validating, in this case, doesnot mean that if John Doe types his name into the form field of a text box as Fred Doe thecomputer sends an alert to inform you that the data is untruthful. No, we still do not have thecapability to find out whether a statement is true.

    Validation is testing to determine whether the user enteredsomethinginto the field. After youdetermine that something was entered, you can then also check to see whether what was enteredis a number or a character and if it is in the correct format. From there, you can compare userinput in different fields or against values that might be held in other repositories, such as adatabase. 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 thatthe data you collect has value and meaning. You ensure this by eliminating any chance that theinformation collected does not abide by the rules you outline.

    Understanding the Difference Between Server-Side and Client-

    Side Validation

    Many people new to ASP.NET don't know the difference between client-side and server-sidevalidation. You must understand these two different ways of validating the data users input into aWeb form.

    After the user enters data into a Web form, clicks the Submit button, and sends the form data tothe server as a request, you can perform server-side validation on the data. If the data is incorrector not valid, you can send back a response stating this. If, however, when the user clicks theSubmit button, a scripting language that is part of the overall HTML page is initiated to checkthe validity of the data before it is sent to the server, this is client-side validation.

    It was a lot easier to understand the difference between these forms of validation when youcoded Active Server Pages 3.0 because, as the programmer, you personally performed almost alldata validation. You yourself either programmed it to be client-side or server-side.

    When you used server-side validation with ASP 3.0, if something the user entered was wrong,you could repost the form and ask the user to correct the information in that particular field of theform. Sometimes, you carried the correct input from the other fields back to the form page, andpopulated the fields for the users so they didn't have to re-enter the same information again.Some sites on the Internet don't carry this inputted information back to the form page, and theuser 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 moreannoying to a user who is on a dial-up connection than clicking the Submit button on the formand then waiting for 20 seconds to find out that they didn't enter their password correctly.

  • 8/8/2019 ASPInput Validation Control

    13/57

    The other option for form validation is to put some client-side JavaScript or VBScript at the topof the ASP page that checks if the information in the fields is correct. This takes care of theproblem of making unnecessary trips to the server, but it requires another language to learn andmanage. JavaScript is a great language, but takes a lot of time to master, and there are alwaysproblems getting your JavaScript code to work on different browsers. Listing 1 shows you an

    example of using client-side JavaScript to perform form validation.

    Listing 1: Client-side JavaScript for 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 onlywhether the user entered anything at all in all five fields within the form. It does not determinewhether the user entered an actual e-mail address within the e-mail address text box, whether theuser entered a number between two given numbers, or whether the password and the confirmpassword text boxes match. After awhile, you can see that you need many JavaScript functionsto obtain the level of form validation required.

    .NET to the Rescue!

    Developers who used classic Active Server Pages 3.0 to develop Web pages might rememberthat they used to spend a considerable amount of their time developing validation mechanics intheir pages. It was time consuming if you did it right. It was most efficient to do the validation of

    the form on the client-side to limit the number of requests and responses required to workthrough an application. As I stated, however, you were never quite sure if the requesting browserwould understand the scripting code that you used for the validation. So, it was usually better,especially for critical Web applications, to bring the validation to the server.

    ASP.NET has changed this by giving you the capability to use the validation server controls thatare provided with the other new controls at your disposal. What makes these validation servercontrols effective is that when an ASP.NET page containing these controls is requested, it is the

  • 8/8/2019 ASPInput Validation Control

    14/57

    ASP.NET engine that decides whether to perform the validation on the client or on the serverdepending on the browser that is making the request. Therefore, your page's functionalitychanges depending on the requesting browserthus enabling you to make your Web pages thebest they can possibly berather than dummying-down your Web applications for the lowestcommon denominator.

    Validation server controls are the only type of ASP.NET server controls that also generate client-side script. All the other controls work with the idea of making postbacks to the server (a requestto the server to get a response).

    Presently, six different validation server controls are available for ASP.NET:

    RequiredFieldValidator CompareValidator RangeValidator RegularExpressionValidator CustomValidator ValidationSummary

    You can also customize validation for your own needs. Then, if there are any errors in the formdata, these validation server controls enable you to customize the display of error information onthe browser.

    You place validation server controls on your page as you would any other type of controls. Afterthe user submits the form, the user's form information is sent to the appropriate validationcontrol, where it is evaluated. If the information doesn't validate, the control sets a page propertythat indicates this. After all the form information is sent to all the validation server controls, ifone 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

    Validation Server

    ControlDescription

    RequiredFieldValidato

    rEnsures that the user does not skip a form entry field

    CompareValidator

    Allows for comparisons between the user's input and another

    item using a comparison operator (equals, greater than, less

    than, and so on)

    RangeValidatorChecks the user's input based upon a lower- and upper-level

    range of numbers or characters

  • 8/8/2019 ASPInput Validation Control

    15/57

    RegularExpressionVali

    dator

    Checks that the user's entry matches a pattern defined by a

    regular expression. This is a good control to use to check e-

    mail addresses and phone numbers

    CustomValidator Checks the user's entry using custom-coded validation logic

    ValidationSummaryDisplays 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, orLinkButton control on the page that submits the form and causes the validation to initiate. Thismight not be the functionality that you are always looking for in your Web forms. You may notwant 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 ofthese buttons, you don't want that button click to validate the contents contained in the Webform.

    To prevent this, you have to set the CausesValidation property for the control to False.

    The RequiredFieldValidator Control

    The RequiredFieldValidator server control makes sure that the user enters something into thefield that it is associated with in the form. You need to tie the RequiredFieldValidator to eachcontrol that is a required field in the form. Although this is the simplest of the validation servercontrols, you must understand certain things about it.

    To see an example of using the RequiredFieldValidator server control, create a Web form thatcontains a TextBox server control and a Button server control. Next to the button, place aRequiredFieldValidator server control. Your ASP.NET page should look like the code illustratedin Listing 2.

    Listing 2: Using the RequiredFieldValidator control

    Visual Basic .NET

    Sub Button1_Click(sender As Object, e As EventArgs)Label1.Text = "Page is valid!"

    End Sub

  • 8/8/2019 ASPInput Validation Control

    16/57

    Visual C# .NET

    void Button1_Click(Object sender, EventArgs e) {Label1.Text = "Page is valid!";

    }

  • 8/8/2019 ASPInput Validation Control

    17/57

    Run this page and then omit putting a value in the text box. When you click the button, you get aresult 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 inyour ASP.NET pages. First of all, the most important property of this validation control is theControlToValidate 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 canlink only one RequiredFieldValidator server control to any other server control on the page. Forinstance, if you have three required TextBox controls on your ASP.NET page, you need threeseparate 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:

    Or you can use the following construct:

  • 8/8/2019 ASPInput Validation Control

    18/57

    Required!

    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 codegenerated to perform the validation is client-side. To see this, right-click the page, and then clickView 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 boxon the page is done client-side. To test this, simply click the button on the page, and you see theRequired! 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 servercontrols. 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:

    Enter something

    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

  • 8/8/2019 ASPInput Validation Control

    19/57

    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.

    Double-Checking Client-Side Validation

    One interesting point is that even though the form data is validated on the client (eliminating theneed for additional requests to and responses from the server to validate the data), the dataentered is re-verified on the server. After the data is checked on the client and found valid, it isrechecked on the server using the same validation rules. These are rules that you establish toensure against some tricky programmer out there trying to bypass the validation process byposting the page to the server as if it passed validation.

    Using the InitialValue Property with a TextBox Server Control

    Another property to be aware of when working with the RequiredFieldValidator server control isthe InitialValue property. Instead of being empty, HTML form elements can be populated

    with default values. In this case, you expect the user to change the value in these elements.

    This situation is illustrated in the Listing 3, which shows a TextBox server control with anassociated RequiredFieldValidator server control.

    Listing 3: A TextBox control with a default value

    Hello

    In this example, the single text box has a default value ofHello. The value you place here can be

    from any source, even a dynamic source. There is also a RequiredFieldValidator server controlthat is assigned to validate this text box. In this case, you want the user to change the initial valueof 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 populatethe TextBox server control from a dynamic source.

    RequiredFieldValidator1.InitialValue = some value

    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 theserver. If the user changes the value in the text box and submits the form, thisRequiredFieldValidator control does not fire and the form is posted.

  • 8/8/2019 ASPInput Validation Control

    20/57

    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 TextBoxcontrol, 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 RequiredFieldValidatorserver 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 associatedwith. The second RequiredFieldValidator control validates that the same text box is not leftempty, as illustrated in Listing 4.

    Listing 4: A single TextBox control with two RequiredFieldValidator controls

    Hello

    Using the InitialValue Property with a DropDownList Control

    A good way of using the InitialValue property is with the DropDownList server control. For

    instance, a drop-down list might have a default value that is not an empty value (by default, sometext appears in it). An example of a drop-down list with the RequiredFieldValidator that uses theInitialValue property is illustrated in Listing 5.

    Listing 5: Using the RequiredFieldValidator server control with the Drop-DownList server

    control

    Select a professionProgrammerLawyerDoctorArtist

  • 8/8/2019 ASPInput Validation Control

    21/57

    ControlToValidate="DropDownList1"InitialValue="Select a profession">

    Using this kind of construct enables you to place a description of the actions required in thedrop-down 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 ofcode to write your own JavaScript function for this procedure, and that JavaScript also has to bebrowser-independent. With ASP.NET, the RequiredFieldValidator server control takes care ofthat.

    Figure 3: Validation error based upon the DropDownList control

    The CompareValidator Control

    The CompareValidator server control compares the value entered into the form field to anotherfield, a database value, or other value that you specify. When comparing against data types, youjust set the OperatorDataTypeCheck. After that is done, you can set the Type attribute to

    String, Integer, Double, Date, orCurrency in the CompareValidator control to make sure that

    the user's input into the field is the specified type.

    Validating Against Other Controls on the Web Form

    Using the CompareValidator server control, you can make comparisons between differentcontrols within a form on your ASP.NET page. For example, if you want to compare what theuser enters in the Password field to the entry in the Confirm Password field to see whether theyare the same, you can use the CompareValidator server control. Using these two fields is a

  • 8/8/2019 ASPInput Validation Control

    22/57

    common practice when a form asks for a password. It ensures that the user doesn't mistype thepassword (see Listing 6).

    Listing 6: Using the CompareValidator server control

    Visual Basic .NET

    Sub Button1_Click(sender As Object, e As EventArgs)Label1.Text = "Passwords match"

    End Sub

    Password

    Confirm Password

    Visual C# .NET

    void Button1_Click(Object sender, EventArgs e) {Label1.Text = "Passwords match";

    }

  • 8/8/2019 ASPInput Validation Control

    23/57

    Password

    Confirm Password

    In this example, the Web form uses two TextBox server controls. One is for the user to enter thepassword, and the second TextBox control requires the user to enter the password again to ensurethey didn't mistype the original. By using the CompareValidator server control, you guaranteethat 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.

  • 8/8/2019 ASPInput Validation Control

    24/57

    Figure 4: In this example, the user mistyped the password and got an error message.

    Validating Against Constants

    You can also use the CompareValidator server control to make sure that the value typed into theform field by a user is valid when compared against a constant, some dynamic value that youretrieve, or that it adheres to a specific data type. Listing 7 shows an example of this.

    Listing 7: Checking to make sure value entered is of a specific data type

    Age:

    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 ofthe CompareValidator server control a value ofInteger, 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 alsoensuring that values are valid when compared against certain constants (see Listing 8).

    Listing 8: Comparing values against constants for validity

  • 8/8/2019 ASPInput Validation Control

    25/57

    Age:

    In this case, a few checks are made against any value that the user types in the text box. The firstis based on the Type property in the CompareValidator server control. The Type property has the

    value ofInteger, 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 ofGreaterThan,

    meaning that for the form submission to be valid, the value entered in the text box has to begreater than the value that is assigned to the ValueToCompare property. For this

    CompareValidator server control, the ValueToCompare property has a value of18. 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 controldisplays an error message in the browser.

    In the situation shown in Listing 8, you are not comparing two fields in the form; instead, you arecomparing one field against a value that you have specified in code. The Operator property can

    contain one of the following values:

    Equal

    NotEqual

    GreaterThan

    GreaterThanEqual

    LessThan

    LessThanEqual

    DataTypeCheck

    The RangeValidator Control

    The RangeValidator server control is similar to the CompareValidator server control, but theRangeValidator server control compares what is entered into the form field with two values andmakes sure that what was entered by the user is between these two specified 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 bebetween a specific range of numbers. For this, you use the RangeValidator server control, asillustrated in Listing 9.

    Listing 9: Using the RangeValidator server control to work with a range of numbers

    Age:

  • 8/8/2019 ASPInput Validation Control

    26/57

    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 andconsiders 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 theDate 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 lastname, and you want only people with last names starting with M and P to proceed, you caneasily 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:

    In the example in Listing 10, the value is being checked against a range that is specified by usingthe 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 ofString.

    The RegularExpressionValidator Control

    The RegularExpressionValidator server control is a validation control that enables you to checkthe user's input based on a pattern defined by a regular expression. This is a great control tocheck whether the user has entered a valid e-mail address or telephone number. In the past, thesekinds of validations took a considerable amount of JavaScript coding. TheRegularExpressionValidator control with ASP.NET saves coding time.

    In the Properties window for the RegularExpressionValidator server control, click the button inthe ValidationExpression box, and Visual Studio.NET provides you with a short list ofexpressions to use in your form via the Regular Expression Editor. However, you are not limited

  • 8/8/2019 ASPInput Validation Control

    27/57

    to these regular expressions in your ASP.NET applications. The list of prepared expressions isshown in Figure 5.

    Figure 5: The Regular Expression Editor

    For an example of using the RegularExpressionValidator server control to make sure that a valueentered in a text box is an e-mail address, look at Listing 11.

    Listing 11: Validating an e-mail address

    Email:

    In this example, notice that you place the Internet e-mail address regular expression in yourValidationExpression 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-mailaddress in the text box.

  • 8/8/2019 ASPInput Validation Control

    28/57

    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 atRegExLib.com.

    Using Images for Your Error Messages

    One interesting way of showing your error messages when using validation controls is to useimages along with text for identifying errors on your ASP.NET pages. This secret is not limited

    to the RegularExpressionValidator server control, but can be used with all the validation servercontrols.

    To use an image instead of text for your error messages, you create something similar to the codein Listing 13.

    Listing 13: Using images for your validation messages

    Email:

    To use an image instead of text for your error messages, you use an HTML string that points tothe image that you want to display for the value of the ErrorMessage property (see Figure 7).

    http://www.regexlib.com/http://www.regexlib.com/
  • 8/8/2019 ASPInput Validation Control

    29/57

    Figure 7: An image is displayed when the incorrect e-mail address is entered.

    The CustomValidator Control

    You are not limited to the validation controls that have been shown thus far in this article; youalso have the CustomValidator server control. The CustomValidator server control enables youto develop your own custom server-side or client-side validations. At times, you may want tocompare the user's input to a value in a database, or to determine whether his input conforms tosome arithmetic validation that you are looking for (for instance, if the number is even or odd).You can do all this and more by using this type of validation control.

    Client-side Validation

    One of the cool things about using the validation controls, in general, is that they allow forclient-side validation of certain HTML server controls. As I said, you can create your ownJavaScript functions that provide you with a higher level of validation capabilities.

    Listing 14 illustrates how to use JavaScript and the CustomValidator server control to expandupon the default validation capabilities that are provided to you with the .NET Framework.

    Listing 14: Creating your own client-side validation functions

    Visual Basic .NET

    Sub Button1_Click(sender As Object, e As EventArgs)Label1.Text = "VALID NUMBER!"

    End Sub

  • 8/8/2019 ASPInput Validation Control

    30/57

    function validateNumber(oSrc, args) {

    args.IsValid = (args.Value % 5 == 0);}

    Number:

    Visual C# .NET

    void Button1_Click(Object sender, EventArgs e) {Label1.Text = "VALID NUMBER!";

    }

    function validateNumber(oSrc, args) {args.IsValid = (args.Value % 5 == 0);

    }

    Number:

  • 8/8/2019 ASPInput Validation Control

    31/57

    The important part of the CustomValidator server control here is theClientValidationFunction 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 eitherTrue orFalse 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 JavaScriptfunctions into ASP.NET controls so that they behave like the other validation controls.

  • 8/8/2019 ASPInput Validation Control

    32/57

    Server-side Validation

    The other way of performing validation on Web forms using the CustomValidator server controlis 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 validationcapabilities. Listing 15 shows you a not-too-elaborate example of server-side checking. Here thecode 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 Basic .NET

    Sub Button1_Click(sender As Object, e As EventArgs)

    If Page.IsValid ThenLabel1.Text = "VALID ENTRY!"

    End IfEnd Sub

    Sub ValidateNumber(sender As Object, args As ServerValidateEventArgs)

    TryDim num As Integer = Integer.Parse(args.Value)args.IsValid = ((num mod 5) = 0)

    Catch ex As Exceptionargs.IsValid = false

    End TryEnd Sub

    Number:

  • 8/8/2019 ASPInput Validation Control

    33/57

    Visual C# .NET

    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;}

    }

    Number:

  • 8/8/2019 ASPInput Validation Control

    34/57

    Performing custom server-side validation with the CustomValidator server controls requires thatyou 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 nameof the server-side function that you would write in one of the .NET-compliant languages.

    Making Validation More Secure

    If you are going to use the CustomValidator server control for client-side validation, you shouldalso consider re-evaluating the user's input using a server-side validation function.

    It is not too hard for some people to post a form back to your server and bypass or fool the client-side validation. If you re-evaluate the input on the server, you can stop this from occurring,making your ASP.NET applications more secure.

    Using the CustomValidator server control to validate the Checkbox server control

    If you have been working through the examples so far in this article, note that there wasn't avalidation server control in place that was able to validate the CheckBox server control. Don't betoo worried. You can use the CustomValidator server control to work through this control. Youcan use it any time that a validation server control on your page is not using theControlToValidate property. For an example of this, see Listing 16.

    Listing 16: Validating a check box

    Visual Basic .NET

    Sub CustomValidator1_ServerValidate(source As Object, _args As ServerValidateEventArgs)

    args.IsValid = (CheckBox1.Checked = True)End Sub

    Sub Button1_Click(sender As Object, e As EventArgs)

    If Page.IsValid Then

    Label1.Text = "Thank you for your donation!"Else

    Label1.Text = ""End If

    End Sub

  • 8/8/2019 ASPInput Validation Control

    35/57

    Check checkbox if you want to donate $10

    Visual C# .NET

    void CustomValidator1_ServerValidate(Object source,ServerValidateEventArgs args) {

    args.IsValid = (CheckBox1.Checked == true);}

    void Button1_Click(Object sender, EventArgs e) {if (Page.IsValid) {

    Label1.Text = "Thank you for your donation!"; }else {

    Label1.Text = "";}

    }

    Check checkbox if you want to donate $10

  • 8/8/2019 ASPInput Validation Control

    36/57

    Note that a CheckBox server control appears on the page. Also notice that there isn't a validationserver 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 functioncalled CustomValidator1_ServerValidate.

    Within this server-side function, validation performed in the code checks whether the CheckBoxserver control's Checked property has a value ofTrue (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 youcan think of. This is a great control to use if you do any database validations on the input that isentered into a form by a user. This control can also apply any complicated logic that you want to

    include in the validation process.

    The ValidationSummary Control

    The ValidationSummary server control works with all the validation server controls on the page.It takes all the error messages that the other validation controls send back to the page and putsthem all in one spot (that you specify) on the page. These error messages can be displayed in alist, bulleted list, or paragraph.

    Showing a Bulleted List of Errors

    You can use the ValidationSummary server control in a number of ways, but the example inListing 17 shows you how to use it in a simple manner. For this example, two text boxes on thepage are associated with a RequiredFieldValidator control. When an error is triggered, not onlydoes it display the error next to the text box itself, it also displays it in a summary at the bottomof the ASP.NET page.

    Listing 17: Having a summary of errors appear on the screen

  • 8/8/2019 ASPInput Validation Control

    37/57

    First name

    Last name

    Using this kind of construct, when the validation server control is triggered, error messagessimilar to the ones shown in Figure 9 appear on the screen.

  • 8/8/2019 ASPInput Validation Control

    38/57

    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 pageusing 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 thefollowing:

    BulletList

    List

    SingleParagraph

    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.

    Showing a Dialog Box Containing Error Notifications

    One flexible feature of the ValidationSummary server control is that you can easily show theASP.NET page's errors in a pop-up dialog box. You have the option of showing the summary inthe browser and the dialog box together, or just in the dialog box.

  • 8/8/2019 ASPInput Validation Control

    39/57

    The property that controls whether the message appears in the browser is the ShowSummary

    property. To turn off the display of validation errors in the browser, set the value of theShowSummary 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

    This code produces results similar to those in Figure 10.

    Figure 10: A dialog box showing the page's validation errors

    Understanding the Difference Between the ErrorMessage and

    Text Properties

    In the examples shown so far using the ValidationSummary server control, the error messageswere next to the items that were being validated (the RequiredFieldValidator server controls) andwere displayed within the ValidationSummary server control. One ideal way of presenting this

    validation-error information is to have an asterisk (*) appear next to the HTML form fields inquestion, while the error messages stating what is wrong with the input appear in the list of errorsshown within the ValidationSummary control.

    To accomplish this, you use the specific validation controlsnot the ValidationSummary servercontrol itself. For instance, if there is a RequiredFieldValidator server control validating a textbox, you construct this validation control as shown in Listing 19.

  • 8/8/2019 ASPInput Validation Control

    40/57

    Listing 19: Showing text differently than it is displayed in the ValidationSummary server

    control

    *

    Or:

    By constructing the page's validation server controls, as shown here, using different values forthe 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.

  • 8/8/2019 ASPInput Validation Control

    41/57

    Conclusion

    You can do a lot with validation, far more than this article explains. Validation controls make adeveloper's life a lot easier. (To develop the same type of functionality in the past, a developerhad to sometimes go to extreme JavaScript-coding measures.)

    The powerful thing about using these validation controls is that they are easy to implement.Modifying them is a piece of cake, so you can easily check for all sorts of parameters on theinput generated from your forms.

    Validation and Web controls make an outstanding combination for building smart forms.

    About the Author

    Bill Evjen is an active proponent of .NET technologies and community-based learning initiativesfor .NET. He is a technical director forReuters, the international news and financial services

    company based in St. Louis, Missouri. Bill is the founder and executive director of theInternational .NET Association (INETA), which represents more than 100,000 membersworldwide. Bill is also an author and speaker and has written such books asASP.NETProfessional Secrets,XML Web Services for ASP.NET, Web Services Enhancements, and theVisual Basic .NET Bible (all from Wiley).

    Example codes

    ValidationForm_cs.aspx

    VB Source

    ValidationForm_vb.aspx

    Sign In Form Validation Sample

    http://reuters.com/http://www.ineta.org/http://www.ineta.org/http://www.wiley.com/http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/validation/ValidationForm.src&file=ValidationForm_cs.aspx&lang=C%23+Sourcehttp://treeview_togglenode%28treeview1_data%2C2%2Cdocument.getelementbyid%28%27treeview1n2%27%29%2C%27%20%27%2Cdocument.getelementbyid%28%27treeview1n2nodes%27%29%29/http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/validation/ValidationForm.src&file=ValidationForm_vb.aspx&lang=VB+Sourcehttp://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=%7E/aspnet/samples/validation/ValidationForm.src&file=ValidationForm_vb.aspx&lang=VB+Sourcehttp://treeview_togglenode%28treeview1_data%2C2%2Cdocument.getelementbyid%28%27treeview1n2%27%29%2C%27%20%27%2Cdocument.getelementbyid%28%27treeview1n2nodes%27%29%29/http://treeview_togglenode%28treeview1_data%2C2%2Cdocument.getelementbyid%28%27treeview1n2%27%29%2C%27%20%27%2Cdocument.getelementbyid%28%27treeview1n2nodes%27%29%29/http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=%7E/aspnet/samples/validation/ValidationForm.src&file=ValidationForm_cs.aspx&lang=C%23+Sourcehttp://reuters.com/http://www.ineta.org/http://www.wiley.com/http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/validation/ValidationForm.src&file=ValidationForm_cs.aspx&lang=C%23+Sourcehttp://treeview_togglenode%28treeview1_data%2C2%2Cdocument.getelementbyid%28%27treeview1n2%27%29%2C%27%20%27%2Cdocument.getelementbyid%28%27treeview1n2nodes%27%29%29/http://quickstarts.asp.net/QuickStartv20/util/srcview.aspx?path=~/aspnet/samples/validation/ValidationForm.src&file=ValidationForm_vb.aspx&lang=VB+Source
  • 8/8/2019 ASPInput Validation Control

    42/57

    Sign In Form ValidationSample

    Sign-In Information

    Email Address:

    *

  • 8/8/2019 ASPInput Validation Control

    43/57

    Not a valid e-mail address. Must [email protected]. Password:

    *

    Password must include one of these (!@#$

    %^&*+;:) Re-enter

    Password:

  • 8/8/2019 ASPInput Validation Control

    44/57

  • 8/8/2019 ASPInput Validation Control

    45/57

    Address: State: Zip Code:

    Zip code must be 5 numeric digits

    Phone:

  • 8/8/2019 ASPInput Validation Control

    46/57

    *

    Must be in form: (XXX) XXX-XXXX

    Credit Card

    Information Card Type: MasterCard

    Visa

  • 8/8/2019 ASPInput Validation Control

    47/57

    *

    Card Number:

    *

    Not a valid credit card number. Must contain 16

    digits.

    Expiration Date: 06/00 07/00 08/00 09/00

    10/00 11/00 01/01 02/01 03/01 04/01 05/01 06/01

  • 8/8/2019 ASPInput Validation Control

    48/57

    07/01 08/01 09/01 10/01 11/01

    12/01

    *

    function ccClientValidate(source, arguments){

    var cc = arguments.Value;

    var ccSansSpace;var i, digits, total;

    // SAMPLE ONLY. Not a real world actual credit cardalgo.

    // Based on ANSI X4.13, the LUHN formula (also knownas the modulus 10 -- or mod 10 -- algorithm )

    // is used to generate and/or validate and verifythe accuracy of some credit-card numbers.

    // Get the number, parse out any non digits, should

    have 16 leftccSansSpace = cc.replace(/\D/g, "");if(ccSansSpace.length != 16) {

    arguments.IsValid = false;return; // invalid ccn

    }

    // Convert to array of digits

  • 8/8/2019 ASPInput Validation Control

    49/57

    digits = new Array(16);for(i=0; i

  • 8/8/2019 ASPInput Validation Control

    50/57

    Sign In Form ValidationSample

    Sign-In Information

    Email Address:

    *

  • 8/8/2019 ASPInput Validation Control

    51/57

    Display="Static" ValidationExpression="^[\w-]+@[\w-]+\.(com|net|org|edu|mil)$"

    Font-Names="Arial" Font-Size="11" runat="server">Not a valid e-mail address. Must follow

    [email protected].

    Password:

    *

    Password must include one of these (!@#$

    %^&*+;:) Re-enterPassword:

  • 8/8/2019 ASPInput Validation Control

    52/57

    Display="Dynamic" Font-Names="Verdana" Font-Size="12" runat="server">

    *

    Password fields don't match

    Personal Information

    First Name:

    Last Name:

  • 8/8/2019 ASPInput Validation Control

    53/57

    Address: State: Zip Code:

    Zip code must be 5 numeric digits

    Phone:

  • 8/8/2019 ASPInput Validation Control

    54/57

    * Must be in form: (XXX) XXX-XXXX

    Credit CardInformation

    Card Type: MasterCard Visa

    *

  • 8/8/2019 ASPInput Validation Control

    55/57

    Card Number:

    *

    Not a valid credit card number. Must contain 16

    digits. Expiration Date:

    06/00 07/00 08/00 09/00 10/00 11/00 01/01

    02/01 03/01 04/01 05/01 06/01 07/01 08/01 09/01

  • 8/8/2019 ASPInput Validation Control

    56/57

    10/01 11/01 12/01

    *

    function ccClientValidate(source, arguments){

    var cc = arguments.Value;var ccSansSpace;

    var i, digits, total;

    // SAMPLE ONLY. Not a real world actual credit cardalgo.

    // Based on ANSI X4.13, the LUHN formula (also knownas the modulus 10 -- or mod 10 -- algorithm )

    // is used to generate and/or validate and verifythe accuracy of some credit-card numbers.

    // Get the number, parse out any non digits, shouldhave 16 left

    ccSansSpace = cc.replace(/\D/g, "");if(ccSansSpace.length != 16) {

    arguments.IsValid = false;return; // invalid ccn

    }

    // Convert to array of digitsdigits = new Array(16);

  • 8/8/2019 ASPInput Validation Control

    57/57

    for(i=0; i