Form Validation

7
ASP.NET Input Validation Controls Submitted by Andrew Ma on Mon, 01/28/2008 - 17:09. asp.net forms validation Back when we had only ASP, developers who had to write webpages for forms knew that the most tedious part is writing code to validate the user input. User input had to be validated so that malicious use of the pages couldn't be achieve. User input had to be validated so that an incorrect piece of information would not be entered. User input had to be validated so that the information stored was standardized. Yeah, some people had libraries of ASP functions to validate common things such as postal codes (zip codes for you Americans), e-mail addresses, phone numbers, etc. The developers of ASP.NET saw the tedium in always having to check user input. They decided that to simplify our life by including validation controls. ASP.NET validation controls also provide two ways of validation: Server-side or Client-side. The nice thing about these Validation controls is that it will perform client-side validation when it detects the browser is able (unless client-side validation has been disabled). Thus reducing roundtrips. And it will perform server-side where necessary. This client-side/server-side detection and validation is done

description

validation report

Transcript of Form Validation

Page 1: Form Validation

ASP.NET Input Validation ControlsSubmitted by Andrew Ma on Mon, 01/28/2008 - 17:09.

asp.net forms validation

Back when we had only ASP, developers who had to write webpages for forms knewthat the most tedious part is writing code to validate the user input. Userinput had to be validated so that malicious use of the pages couldn't beachieve. User input had to be validated so that an incorrect piece ofinformation would not be entered. User input had to be validated so that theinformation stored was standardized. Yeah, some people had libraries of ASPfunctions to validate common things such as postal codes (zip codes for youAmericans), e-mail addresses, phone numbers, etc. The developers of ASP.NET sawthe tedium in always having to check user input. They decided that to simplifyour life by including validation controls.

ASP.NET validation controls also provide two ways ofvalidation: Server-side or Client-side. The nice thing about these Validationcontrols is that it will perform client-side validation when it detects thebrowser is able (unless client-side validation has been disabled). Thus reducingroundtrips. And it will perform server-side where necessary. Thisclient-side/server-side detection and validation is done without extra work bythe developer!

With ASP.NET, there are five(5) controls included. Theyare:

The RequiredFieldValidation Control The CompareValidator Control The RangeValidator Control The RegularExpressionValidator Control The CustomValidator Control

The validation controls

All of the validation controls inherit from the base class BaseValidator so theyall have a series of properties and methods that are common to all validationcontrols. They are:

ControlToValidate - This value is which control the validator isapplied to.

ErrorMessage - This is the error message that will be displayed inthe validation summary.

Page 2: Form Validation

IsValid - Boolean value for whether or not the control is valid. Validate - Method to validate the input control and update the

IsValid property. Display - This controls how the error message is shown. Here are

the possible options: o None (The validation message is never displayed.) o Static (Space for the validation message is allocated in the page

layout.) o Dynamic (Space for the validation message is dynamically added to the

page if validation fails.)

Now to the five controls themselves:

The RequiredFieldValidation Control

The first control we have is the RequiredFieldValidation Control. As it'sobvious, it make sure that a user inputs a value. Here is how it's used:

Required field: <asp:textbox id="textbox1" runat="server"/><asp:RequiredFieldValidator id="valRequired" runat="server"ControlToValidate="textbox1" ErrorMessage="* Please enter a value" Display="dynamic">*</asp:RequiredFieldValidator>

In this example, we have a textbox which will not be valid until the usertypes something in. Inside the validator tag, we have a single *. The text inthe innerhtml will be shown in the controltovalidate if the control is notvalid. It should be noted that the ErrorMessage attribute is not what isshown. The ErrorMessage tag is shown in the Validation Summary (see below).

The CompareValidator Control

Next we look at the CompareValidator Control. Usage of this CompareValidator isfor confirming new passwords, checking if a departure date is before the arrivaldate, etc. We'll start off with a basic example:

Textbox 1: <asp:textbox id="textbox1" runat="server"/><br />Textbox 2: <asp:textbox id="textbox2" runat="server"/><br /><asp:CompareValidator id="valCompare" runat="server" ControlToValidate="textbox1" ControlToCompare="textbox2" Operator="Equals" ErrorMessage="* You must enter the same values into textbox 1 and textbox 2" Display="dynamic">*</asp:CompareValidator>

Here we have an example where the two textboxes must be equal. The tags that areunique to this control is the ControlToCompare attribute which is the

Page 3: Form Validation

control that will be compared. The two controls are compared with the type ofcomparison specified in the Operator attribute. The Operatorattribute can contain Equal, GreterThan, LessThanOrEqual, etc. Another usage ofthe ComapareValidator is to have a control compare to a value. For example:

Field: <asp:textbox id="textbox1" runat="server"/><asp:CompareValidator id="valRequired" runat="server" ControlToValidate="textbox1" ValueToCompare="50" Type="Integer" Operator="GreaterThan" ErrorMessage="* You must enter a number greater than 50" Display="dynamic">*</asp:CompareValidator>

The data type can be one of: Currency, Double, Date, Integer or String, stringbeing the default data type.

The RangeValidator Control

Range validator control is another validator control which checks to see if acontrol value is within a valid range. The attributes that are necessary to thiscontrol are: MaximumValue, MinimumValue, and Type.

Sample:

Enter a date from 1998:<asp:textbox id="textbox1" runat="server"/><asp:RangeValidator id="valRange" runat="server" ControlToValidate="textbox1" MaximumValue="12/31/1998" MinimumValue="1/1/1998" Type="Date" ErrorMessage="* Date must be between 1/1/1998 and 12/13/1998" Display="static"> *</asp:RangeValidator>

The RegularExpressionValidator Control

The regular expression validator is one of the more powerful features ofASP.NET. Everyone loves regular expressions. Especially when you write thosereally big nasty ones- and then a few days later, look at it and say to yourself:what does this do?

Again, the simple usage is:

E-mail: <asp:textbox id="textbox1" runat="server"/><asp:RegularExpressionValidator id="valRegEx" runat="server" ControlToValidate="textbox1"

Page 4: Form Validation

ValidationExpression=".*@.*\\..*" ErrorMessage="* Your entry is not a valid e-mail address." display="dynamic">*</asp:RegularExpressionValidator>

Here is a service I like to use to checkmy regular expressions for validity.

The CustomValidator Control

The final control we have included in ASP.NET is one that adds great flexibilityto our validation abilities. We have a custom validator where we get to writeour own functions and pass the control value to this function.

Field: <asp:textbox id="textbox1" runat="server"><asp:CustomValidator id="valCustom" runat="server" ControlToValidate="textbox1" ClientValidationFunction="ClientValidate" OnServerValidate="ServerValidate" ErrorMessage="*This box is not valid" dispaly="dynamic">*</asp:CustomValidator>

You'll notice that there are two new attributes ClientValidationFunctionand OnServerValidate. These are to tell the validation control whichfunctions to pass the controltovalidate value to. ClientValidationFunction isusually a JavaScript function included in the HTML of your webpage. OnServerValidate

is the function that is server-side to check for validation if client does notsupport client-side validation.

Client Validation function:

<script language="Javascript"><!-- /* ... Code goes here ... *///--></script>

Server Validation function:

Sub ServerValidate (objSource As Object, objArgs As ServerValidateEventsArgs) ' Code goes hereEnd Sub

Validation Summary

ASP.NET has provided an additional control that complements the validatorcontrols. This is the validation summary control which is used like:

Page 5: Form Validation

<asp:ValidationSummary id="valSummary" runat="server" HeaderText="Errors:" ShowSummary="true" DisplayMode="List" />

The validation summary control will collect all the error messages of all thenon-valid controls and put them in a tidy list. The list can be either shown onthe web page (as shown in the example above) or with a popup box (by specifying ShowMessageBox="True")

Now you know how to use the Validator Controls in ASP.NET! Have fun!

Acknoledgment: Professional ASP.NET (published by Wrox) wasused a reference. It's a good book!

Tips to remember

If you are doing server-side validation, make sure the button onclickmethod has a Page.IsValid if statement or it will look like your validatorsaren't doing anything

Don't forget to wrap everything in the <form runat=server> tag.