Professional Documents
Culture Documents
Form Validation: Developmentor
Form Validation: Developmentor
developmentor
Objectives
Discuss validation in web applications Client-side validation with javascript Server-side validation Introduce ASP.NET validation architecture Adding validation to a form Client-side validation Server-side validation Inspect validation controls Different validation types Displaying validation summaries Performing custom validation
developmentor
Form Validation
Form validation is commonplace on the web Data entered by users must be validated before it is used by the server Email addresses need to validated Phone numbers must be of the correct form Passwords must be entered twice correctly, and so on...
developmentor
developmentor
Client-side Validation
Data validation can occur on the client side using scripting Reduces round-trips to the server by correcting mistakes before submitting them Provides user with immediate feedback on data input Requires client browser support scripting Can be easily subverted to send bad data to the server anyway (should never use client-side validation without server-side validation too)
developmentor
Client-side script validation example <html><head><script language="javascript"> function checkForm() { var ret = false; if (document.all["cname"].value == "") document.all["err_cname"].style.visibility = "visible"; else if (document.all["email"].value == "") document.all["err_email"].style.visibility = "visible"; else ret = true; return ret; } </script></head> <form name="SIGNUP" method="post" onSubmit="return checkForm()"> <table cellspacing="0" cellpadding="1" border="0"> <tr valign="top"><td align="right"><b>Name:</b></td> <td><input id="cname" /></td> <td><span id="err_cname" style="visibility:hidden;color:red"> Please enter a name here</span></td></tr> <tr valign="top"><td align="right"><b>E-mail address:</b></td> <td><input id="email" /></td> <td><span id="err_email" style="visibility:hidden;color:red"> Please enter your email here</span></td></tr> </table> <input type="submit" value="sign up!" /> </form></body></html>
developmentor
Server-side Validation
Data validation should always occur on the server Before data is actually used on the server, it should typically be validated Even with client-side validation, validation on the server should still occur as a precaution If an error is encountered, the form should be presented to the user again for corrections
developmentor
Validation Observations
Some observations about how validation is performed on the web Error messages often appear adjacent to input elements A list of all errors is often displayed in summary Client-side validation is useful to avoid round trips Server-side validation should always be performed The error message displayed for a given field may change based on the error Field validation may be dependent on the value of another field
developmentor
Validation in ASP.NET
ASP.NET provides a set of controls to perform validation Add validation to a form by adding one or more of these controls Display message boxes and summary paragraphs Perform client-side validation when possible Always perform server-side validation
developmentor
developmentor
10
<asp:TextBox id="foo" runat="server"/> <asp:RequiredFieldValidator id="fooValidator" ControlToValidate="foo" Display="Static" InitialValue="" runat="server" ErrorMessage="The foo field must be completed.">* </asp:RequiredFieldValidator>
developmentor
11
Validator rendering
<asp:RequiredFieldValidator runat="server" ErrorMessage="Enter a Name" ControlToValidate="_name" Display="Static"> *** </asp:RequiredFieldValidator> Renders as <asp:RequiredFieldValidator runat="server" ErrorMessage="Enter a Name" ControlToValidate="_name" Display="Dynamic"> *** </asp:RequiredFieldValidator> Renders as
<span controltovalidate="_name" errormessage="Enter a Name" display="Dynamic" evaluationfunction="RequiredFieldValidatorEvaluateIsValid" initialvalue="" style="color:Red;display:none;"> *** </span> <span controltovalidate="_name" errormessage="Enter a Name" evaluationfunction="RequiredFieldValidatorEvaluateIsValid" initialvalue="" style="color:Red;visibility:hidden;"> *** </span>
developmentor
12
Page Validation
The server-side validation of a form is coordinated by the Page class The Page class maintains a list of all the validation controls in its Validators collection property Each validation control implements the IValidator interface that defines the Validate method, and two properties: ErrorMessage and IsValid The Page class implements a property IsValid that can be checked at any time to discover whether a page is valid The Page class implements a method Validate() that traverses the list of validation controls, invoking each Validate() method in turn to test the validity of a page
developmentor
13
Page
IsValid Validate() Validators
IValidator
val ctrl1
IValidator
val ctrl2
IValidator
val ctrl3
public interface IValidator { string ErrorMessage {get; set;} bool IsValid {get; set;} void Validate(); }
developmentor
14
Server-side Validation
Server-side validation takes place during the post-back sequence Initial values of controls are not validated -- only once the user has submitted the page is server-side validation triggered Validation occurs just after the Page_Load event firing on a post-back sequence If validation fails, server-side validation controls that failed validation render as visible span elements - no other action is taken You must check IsValid() on the Page class before looking at any data submitted by a client
developmentor
15
Page-derived class is created, constructor is invoked IHttpHandler.ProcessRequest method of Page class invoked
virtual CreateChildControls method of Page is invoked Server-side control state is restored from POST variables and VIEWSTATE
Page.Validate() invoked
developmentor
16
Client-side Validation
Client-side validation is implemented in JavaScript and occurs in up-level browsers only A JavaScript file is placed at /aspx_client/system_web/(version)/WebUIValidation.js which contains validation routines (IE compatible only) Each validation control is translated into a span element with custom attributes, and a style of "color:Red;visibility:hidden" A global script variable, Page_Validators is set up with all of the span elements created The ValidatorOnLoad() function is called at startup to wire up validation handlers Can disable by manually setting the clienttarget attribute of the @Page directive to "downlevel"
developmentor
17
Page_Validators[] Page_IsValid
ValidatorOnLoad() Iterates across all validation controls, hooks up change handlers, initializes vars
Page_ClientValidate() Iterates across all validators on the page and validates them
ValidatorUpdateIsValid() Iterates across all validators on the page updating the global Page_IsValid flag
developm
18
developmentor
19
Validation Controls
ASP.NET provides six built-in validation controls RequiredFieldValidator: for verifying that a field is not left empty ValidationSummary: for displaying a summary of all of the error messages on a given form CompareValidator: for comparing the value of a field to another field (or constant) RangeValidator: for verifying that a field value falls within a given range (specified either as constants or other fields) RegularExpressionValidator: for verifying the contents of a field against a regular expression CustomValidator: for building your own validation algorithm
developmentor
20
Validation Control
RequiredFieldValidator CompareValidator
Properties
-Operator Type ValueToCompare ControlToCompare MaximumValue MinimumValue Type ValidationExpression ServerValidate ClientValidationFunction DisplayMode HeaderText ShowMessageBox ShowSummary
Values/Description
-Equal, GreaterThan, LessThan,... Currency, Date, Double, Integer, ... Constant value to compare against Other control to compare against Constant value for upper bound Constant value for lower bound Currency, Date, Double, Integer, ... Regular expression to validate against Server-side validation routine Client-side validation routine BulletList, List, SingleParagraph Title text of summary Display alert? Display summary paragraph?
ValidationSummary
developmentor
21
ValidationSummary control example <table cellspacing=0 cellpadding=2 border=0> <tr><td><table cellspacing=0 cellpadding=1 border=0> <tr><td align=right><b>Name:</b></td> <td><asp:TextBox id="cname" runat=server/></td> <td><asp:RequiredFieldValidator id="cnameValidator" ControlToValidate="cname" Display="Static" ErrorMessage="Name must be filled in." InitialValue="" runat=server>* </asp:RequiredFieldValidator> </td></tr> <tr><td align=right><b>Phone:</b></td> <td><asp:TextBox id="phone" runat=server/></td> <td><asp:RequiredFieldValidator id="phoneValidator" ControlToValidate="phone" Display="Static" ErrorMessage="Phone must be filled in." InitialValue="" runat=server>* </asp:RequiredFieldValidator> </td></tr> <tr><td></td> <td><input value="Enter" type=submit /></td> </tr></table><td> <asp:ValidationSummary id="valSum" runat=server HeaderText="Please correct the following errors:" ShowMessageBox="True"/></td></tr></table>
developmentor
22
<table cellspacing="0" cellpadding="1" border="0"> <tr> <td align="right"><b>Name:</b></td> <td><asp:TextBox id="cname" runat="server"/></td> <td/> </tr> <tr> <td align=right><b>Age:</b></td> <td><asp:TextBox id="age" runat="server"/></td> <td><asp:CompareValidator id="ageValidator" ControlToValidate="age" ValueToCompare="21" Type="Integer" Operator="GreaterThanEqual" runat="server">You must be >= 21! </asp:CompareValidator></td> </tr> <tr> <td></td> <td><input value="Enter" type="submit" /></td> </tr> </table>
developmentor
23
<table cellspacing="0" cellpadding="1" border="0"> <tr> <td align="right"><b>Email address:</b></td> <td><asp:TextBox id="Email" runat="server"/></td> <td><asp:RegularExpressionValidator id="EmailRegexValidator" ControlToValidate="Email" Display="static" ErrorMessage="E-mail must be of the form foo@bar.com." InitialValue="" width="100%" runat="server" ValidationExpression= "[\w-]+@[\w-]+\.(com|net|org|edu|mil)$"> </asp:RegularExpressionValidator></td> </tr> <tr> <td></td> <td><input value="Enter" type="submit" /></td> </tr> </table>
developmentor
24
developmentor
25
CustomValidator control example <html> <body> <form runat="server"> <table cellspacing="0" cellpadding="1" border="0"> <tr> <td align="right"><b>Enter a number:</b></td> <td><asp:TextBox id="num" runat="server"/></td> <td><asp:CustomValidator id="numValidator" ControlToValidate="num" Display="static" InitialValue="" ClientValidationFunction = "MyClientValidationFunction" OnServerValidate = "MyServerValidationFunction" width="100%" runat="server">Wrong! Try again... </asp:CustomValidator></td> </tr> <tr> <td></td> <td><asp:Button Text="Enter" runat="server" /></td> </tr> </table> </form> </body> </html>
developmentor
26
Custom Validator script blocks <script language="javascript"> <!-function MyClientValidationFunction(source, args) { if (args.Value % 3) args.IsValid=false; else args.IsValid=true; } --> </script> <script language="C#" runat="server"> void MyServerValidationFunction(object source, ServerValidateEventArgs e) { e.IsValid = false; try { int num = Convert.ToInt32(e.Value); if (num % 3 == 0) e.IsValid = true; } catch (Exception) {} } </script>
developmentor
27
Summary
Form validation is critical for web applications interacting with users Client-side validation is important for user-friendly data entry Server-side validation is critical for data correctness Validation controls implement IValidate Validation occurs by invoking each control's Validate() method There are six different validation controls available
developmentor
28