08 validation
Post on 14-Apr-2018
220 Views
Preview:
TRANSCRIPT
-
7/29/2019 08 Validation
1/28
1d e v e l o p m e n t o r
Form Validation
-
7/29/2019 08 Validation
2/28
2d e v e l o p m e n t o r
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
-
7/29/2019 08 Validation
3/28
3d e v e l o p m e n t o r
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...
-
7/29/2019 08 Validation
4/28
4d e v e l o p m e n t o r
Sample web validation form
-
7/29/2019 08 Validation
5/28
5d e v e l o p m e n t o r
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)
-
7/29/2019 08 Validation
6/28
6d e v e l o p m e n t o r
function checkForm() {var ret = false;if (document.all["cname"].value == "")document.all["err_cname"].style.visibility = "visible";
elseif (document.all["email"].value == "")document.all["err_email"].style.visibility = "visible";
elseret = true;
return ret;}
Name:Please enter a name here
E-mail address:Please enter your email here
Client-side script validation example
-
7/29/2019 08 Validation
7/28
7d e v e l o p m e n t o r
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 theuser again for corrections
-
7/29/2019 08 Validation
8/28
8d e v e l o p m e n t o r
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
-
7/29/2019 08 Validation
9/28
9d e v e l o p m e n t o r
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
-
7/29/2019 08 Validation
10/28
10d e v e l o p m e n t o r
Adding a validation control to a form
To add a validation control to a form:
Add the appropriate control to your form, at the location where
the error message should appear
Fill in the ControlToValidate field of the control with the ID
of the control you are validating
Fill in the Display field of the control to indicate whether theerror message of this control should occupy space when it is
not visible (static versus dynamic)
Fill in the ErrorMessage of the control with the error
message to be displayed in the summary of all errors on the
form Fill in the contents of the control with whatever html you want
displayed when there is an error
-
7/29/2019 08 Validation
11/28
11d e v e l o p m e n t o r
*
Adding a RequiredFieldValidator control to a form
-
7/29/2019 08 Validation
12/28
12d e v e l o p m e n t o r
***
***
***
***
Renders asRenders as
Validator rendering
-
7/29/2019 08 Validation
13/28
13d e v e l o p m e n t o r
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
itsValidators 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 IsValidthat can be
checked at any time to discover whether a page is valid
The Page class implements a methodValidate() that
traverses the list of validation controls, invoking eachValidate() method in turn to test the validity of a page
-
7/29/2019 08 Validation
14/28
14d e v e l o p m e n t o r
PageIsValid
Validate()
Validators
val
ctrl1
val
ctrl2
val
ctrl3
Validation Controls on this Page
IValidator IValidator IValidator
Validation Controls Architecture
publicinterface IValidator{string ErrorMessage {get; set;}bool IsValid {get; set;}void Validate();
}
-
7/29/2019 08 Validation
15/28
15d e v e l o p m e n t o r
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_Loadevent 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
-
7/29/2019 08 Validation
16/28
16d e v e l o p m e n t o r
Server-side Validation During Post-Back
IHttpHandler.ProcessRequest method ofPage class invoked
Page-derived class is created,constructor is invoked
POST Request issued by client
Init event of Page class fires
virtual CreateChildControls method ofPage is invoked
Server-side control state is restored from POSTvariables and VIEWSTATE
Load event of Page class fires
Server-side control events are fired
PreRender event of Page class fires
virtual Render method of Page class invoked
virtual RenderChildren method ofPage class invoked
Unload event of Page class fires
instance of Page-derived class is discarded
HTTP Response issued to client
Page.Validate() invoked
-
7/29/2019 08 Validation
17/28
17d e v e l o p m e n t o r
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 withcustom 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
TheValidatorOnLoad() function is called at startup to wire
up validation handlers Can disable by manually setting the clienttarget attribute
of the @Page directive to "downlevel"
-
7/29/2019 08 Validation
18/28
18d e v e l o p m e n t o r
Script elements
of client-side
validation
ValidatorUpdateDisplay()Makes text of validatorspan visible ifvalidator is invalid
ValidatorUpdateIsValid()
Iterates across allvalidators on the pageupdating the globalPage_IsValid flag
ValidatorHookupControl()Wires up control changesto ValidatorOnChange()handler
Page_ClientValidate()Iterates across allvalidators on the pageand validates them
ValidatorEnable()Enables or disables agiven validator
ValidatorValidate()
Invokes the validationfunction for a givenvalidator
Page_Validators[]
Page_IsValid
ValidatorOnChange()Handler for change eventson validation controls -invokes validation
ValidatorOnLoad()Iterates across allvalidation controls,hooks up change handlers,initializes vars
Called when
page loads
Called when
form is submitted
Called on
OnChange event
-
7/29/2019 08 Validation
19/28
19d e v e l o p m e n t o r
Valid Controls to Validate
Only a subset of the available controls work with validation
controls
A control must have aValidationPropertyAttribute to
indicate which property to read for validation for it to work with
validation controls
Thevalue
attribute of a control must correspond to its value
to validate for client-side validation to work
Controls That Work With Validation
HTMLInputText
HTMLTextArea
HTMLSelectHTMLInputFile
TextBox
DropDownList
ListBox
RadioButtonList
-
7/29/2019 08 Validation
20/28
20d e v e l o p m e n t o r
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 toanother 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
-
7/29/2019 08 Validation
21/28
21d e v e l o p m e n t o r
CompareValidator
RangeValidator
RegularExpressionValidator
Validation Control
RequiredFieldValidator
OperatorTypeValueToCompareControlToCompare
Properties
CustomValidator
ValidationSummary
Equal, GreaterThan, LessThan,...Currency, Date, Double, Integer, ...Constant value to compare againstOther control to compare against
MaximumValueMinimumValueType
Constant value for upper boundConstant value for lower boundCurrency, Date, Double, Integer, ...
-- --
Validation-Expression Regular expression to validateagainst
ServerValidateClientValidation-Function
Server-side validation routineClient-side validation routine
DisplayModeHeaderTextShowMessageBoxShowSummary
BulletList, List, SingleParagraphTitle text of summaryDisplay alert?Display summary paragraph?
Values/Description
Validation controls and their properties
-
7/29/2019 08 Validation
22/28
22d e v e l o p m e n t o r
Name:
*
Phone:
*
ValidationSummary control example
-
7/29/2019 08 Validation
23/28
23d e v e l o p m e n t o r
Name:
Age:You must be >= 21!
CompareValidator control example
-
7/29/2019 08 Validation
24/28
24d e v e l o p m e n t o r
Email address:
RegularExpressionValidator control example
-
7/29/2019 08 Validation
25/28
25d e v e l o p m e n t o r
Character Meaning
[...] Match any one character between brackets
[ ...] Match any one character not between brackets
. Match any one character not between brackets
\w Match any word character [a-zA-Z0-9_]
\W Match any whitespace character [\t\n\r\f\v]
\s Match any non-whitespace character [ \t\n\r\f\v]
\d Match any digit [0-9]
\D Match any non-digit character [ 0-9]
[\b] Match a l iteral backspace
{n,m} Match the previous item >= n times, = n times
{n} Match the previous item exactly n times
? Match zero or one occurrences of the previous item {0,1}
+ Match one or more occurrences of the previous item {1,}
* Match zero or more occurrences of the previous item {0,}
| Match either the subexpression on the left or the right
(...) Group items together in a unit
^ Match the beginning of the string
$ Match the end of the string
\b Match a word boundary
\B Match a position that is not a word boundary
Some Regular Expression characters and their meaning
-
7/29/2019 08 Validation
26/28
26d e v e l o p m e n t o r
Enter a number:Wrong! Try again...
CustomValidator control example
-
7/29/2019 08 Validation
27/28
27d e v e l o p m e n t o r
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){}
}
Custom Validator script blocks
-
7/29/2019 08 Validation
28/28
28d e v e l o p m e n t o r
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
top related