ASP.NET server controls

Download Report

Transcript ASP.NET server controls

ASP.NET
Validating user input
Validating user input on the client
and/or server side
ASP.NET Validating User Input
1
Validation
• Goals
– Check validity of data from the end user
• How
– Check user input on the client side or on the
server side
• Examples
– Is the name TextBox empty?
– Does the email TextBox contain a structurally
valid email address?
ASP.NET Validating User Input
2
Client-side vs. server-side
validation
• Client-side validation
– Done in the browser
– Uses JavaScript
• Users can disable
JavaScript!
• Different browsers →
different JavaScript
versions
• Server-side validation
– Done on the server
– Uses C#
– Requires HTTP
request + response
– Does not require HTTP
request + response
ASP.NET Validating User Input
3
Client-side and server-side
validation
• Best practice
– Client-side validation and server-side
validation
– Client-side saves time
• No HTTP request/response
– Server-side
• Provides security
– JavaScript not disable
ASP.NET Validating User Input
4
ASP.NET Validation server controls
• ASP.NET performs browser detection
– Client supports JavaScript
• Use client-side validation + server-side validation
– Client does not support JavaScript
• Use server-side validation
ASP.NET Validating User Input
5
The standard validation controls
•
RequiredFieldValidator
– Input field cannot be empty
•
CompareValidator
– Compare between user inputs using =, >, etc.
•
RangeValidator
– Minimum < input < maximum
•
RegularExpressionValidator
– Check the entry matches a pattern defined by the regular expression
•
CustomValidator
– Make your own validator
•
DynamicValidator
– Advanced: Exceptions thrown from the model
•
ValidationSummary
– Displays all error messages from validators in one spot
•
Third-party controls
– Not made by Microsoft or by you
– Examples: www.peterblum.com/DES
ASP.NET Validating User Input
6
Some properties common to all
validation controls
• ControlToValidate
– The control to be validated
• ErrorMessage
– The message used in the ValidationSummary
• Text
– The error message used in the validation control
• CssClass
– Style appearance of the messages
• Example: aspnet/validation/Validation
ASP.NET Validating User Input
7
Making validation happen – or not
• Validation happens because of an event
– Example: button click event
– Can be turned of (for some buttons in a form)
• <asp:Button ID=“Button1” runat=“server”
Text=“Submit” CausesValidation=“false” >
• Client-side validation can be turned off
– Only server-side validation in effect
– <asp:RequiredFieldValidator …
EnableClientScript=“false”>
ASP.NET Validating User Input
8
References
• Bill Evjen et al. Professional ASP.NET 4
in C# and VB, Wrox 2010
– Chapter 4, Validation Server Controls, page
157-185
• W3schools.com Validation Server Controls
– http://w3schools.com/aspnet/aspnet_refvalida
tioncontrols.asp
ASP.NET Validating User Input
9