Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 9 Validating User Input. Objectives What user input is and why it’s important to validate it What ASP.NET 4.5.1 has to offer to aid you in validating.

Similar presentations


Presentation on theme: "Chapter 9 Validating User Input. Objectives What user input is and why it’s important to validate it What ASP.NET 4.5.1 has to offer to aid you in validating."— Presentation transcript:

1 Chapter 9 Validating User Input

2 Objectives What user input is and why it’s important to validate it What ASP.NET 4.5.1 has to offer to aid you in validating user input How to work with the built-in validation controls and how tocreate solutions that are not supported out of the box How to send e-mail using ASP.NET How to read text files

3 Obtaining Data from the user Data is obtained from the user to the server side through different ways. To common ways are using a GET and POST GET sends data through to the actual address via the Querytring POST sends data through the body of the request of the page The Request Object contains a QueryString property which shows what is sent over the QueryString http://www.PlanetWrox.com/Reviews/ViewDetails.aspx?ReviewId=34&CategoryId =3 The question mark is used to separate the query string from the rest of the address, and the query string itself consists of name/value pairs separated by an ampersand ( & ). The names and values in turn are separated by theequals symbol ( = ).

4 Obtaining Data from the user To obtain values from the QueryString, you can use the Get Method in the Request object: // Assigns the value 34 to the reviewId variable int reviewId = Convert.ToInt32(Request.QueryString.Get("ReviewId")); // Assigns the value 3 to the categoryId variable int categoryId = Convert.ToInt32(Request.QueryString.Get("CategoryId")); How can we be sure that the data we obtain from the user is going to be convert correctly to an “Int” in this case? What’s to prevent the user from using an alphabetic character?

5 Validation To protect your application you should always perform some validation of the data. Client Side Validation: This is done mostly for the convenience of the user. It saves them a poastback trip to find out that their input is incorrect. Server Side Validation: This is where the validation should occur to truly be able to protect your website. THIS IS A MUST HAVE. Why don’t we rely on just client side validation? Client side validation is done by Javascript, and this can be easily tampered with by the user. Modern browsers allow uses to explore the client side code and make changes to it.

6 ASP.NET Validation Controls.NET provides several validation controls: CompareValidator CustomValidator: Uses a custom logic to validate RangeValidator: Evaluates a range RegularExpressionValidator: Evaluates against a reg expression RequiredFieldValidator: Makes sure the field has been populated ValidationSummary: Provides feedback to users about errors

7 Required Field Validator Validation Controls can check in the client side and the server side. Required Field Validator: Add the control to the ASPX page The ControlToValidate tag points to another control which will be bound to this validation The Error Message is the message displayed to the user if this validation fails. You can use a CSS class to decorate the error message and the Text Field to denote the field as required if the user doesn’t fill in any data

8 Required Field Validator Create a class to drive the design of the error message.ErrorMessage { color: Red; } Whenever you try to submit the form to the server by clicking the Send button, the validation control checks the control it is attached to. When the text box is still empty, the asterisk from its Text property is shown (formatted with the ErrorMessage CSS class), and the form is not submitted.

9 HTML 5 Input Data Types ASP.NET Textboxes support these types with the TextMode Attribute.

10 HTML 5 Input Data Types When Rendered the following HTML is outputted These data types are supported by most modern browsers and have additional functionality that affects behavior on smartphones or tables. See these when possible as browsers get more HTML 5 support. Demo: http://imar.spaanjaars.com/demos/html5/html5.aspx

11 Common Validation Control Properties These are the common properties of the Validation controls since they inherit from the same base class.

12 Common Validation Control Properties

13 Difference between Text and ErrorMessage Both appear to do the same thing, but they are different. When you set both the properties at the same time, the validation control displays the Text property, whereas the ValidationSummary uses the ErrorMessage. The Text property sets the “*” while ValidationSummary prints the ErrorMessage.

14 Range Validator This validator allows to check for a certain range and can check strings, numbers, dates and currencies <asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="Rate" ErrorMessage="Enter a number between 1 and 10" MaximumValue="10" MinimumValue="1" Type="Integer" />

15 Regular Expression Validator Validates against a regular expression, which is a powerful rule that ca be created to specify a particular pattern. Some built-in expression in Visual Studio are email and Zip. <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="Email" ErrorMessage="Enter a valid e-mail address" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" />

16 Compare Validator Compares the value of one control to another or a constant. For example can be used to compare two password fields to make sure they match.

17 Compare Validator Compare two textbox passwords. One textbox has the id of “Password” The other textbox has the id of “ConfirmPassword” Since no operator is set, it defaults to Equality comparison. <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToCompare="ConfirmPassword" ControlToValidate="Password" ErrorMessage="Your passwords don't match" />

18 Custom Validator and Validation Summary With the customer validator, you can define client side validation with your on method and server side validation with your own server side method. * The Server Side validate tests the following protected void CustomValidator1_ServerValidate(object source,ServerValidateEventArgs args) { if (!string.IsNullOrEmpty(PhoneHome.Text) || !string.IsNullOrEmpty(PhoneBusiness.Text)) { args.IsValid = true; } else { args.IsValid = false; }

19 Custom Validator and Validation Summary The Client Side validation script is the following: function validatePhoneNumbers(source, args) { var phoneHome = document.getElementById(' '); var phoneBusiness = document.getElementById(' '); if (phoneHome.value != '' || phoneBusiness.value != '') { args.IsValid = true; } else { args.IsValid = false; } The tests check that either the home or business phone is populated.

20 Validation Summary Control The ValidationSummary control provides the user with a list of errors that it retrieves from the individual validation control’s ErrorMessage properties. It can display these errors in three different ways: using a list embedded in the page, using a JavaScript alert box, or using both at the same time. You control this setting with the ShowMessageBox and ShowSummary properties. Additionally, the DisplayMode property enables you to change the way the list of errors is presented. The default setting is BulletList where each error is an item in a bulleted list, but other options are List (without bullets) and SingleParagraph.

21 Validation Summary Control If we change ShowMessageBox to True, we get an Alert Box with the error messages.

22 Request Validation By default, ASP.NET throws an exception if someone tries to add HTML syntax inside a control to prevent malicious code.

23 Request Validation You can disable this to allow users to enter HTML syntax. At the Page level (Allows all controls to accommodate HTML syntax): At a Control level: The Control class contains the ValidateRequestMode property, when set to “disabled” it accepts HTML. If you allow HTML, you must sanitize the data to remove dangerous pieces of code, such as removing elements. When displaying the data on a page, you could use a Literal control, with its Mode set to Encode in order for the HTML to be encoded and rendered harmless. With this property set, the text is displayed verbatim, without being interpreted as HTML or JavaScript.

24 Sending Email from Your Website Inside the System.Net.Mail namespace you find a number of classes that make it easy to create and send e-mail messages.

25 Configuring the mail server To Send Email you need to have the SMTP Server configuration which can be setup in web.config of the site.... Other configurations require other settings such as username,password, or SSL.

26 Creating a Mail Message To send an email, you need to create a MailMessage Object and set the properties of the message,such as To and From address, Body and Subject. Once the Mail Message is formed, it is sent to an SmtpClient Object. protected void Page_Load(object sender, EventArgs e) { MailMessage myMessage = new MailMessage(); myMessage.Subject = "Test Message"; myMessage.Body = "Hello world, from Planet Wrox"; myMessage.From = new MailAddress("you@example.com", "Sender Name"); myMessage.To.Add(new MailAddress("you@example.com", "Receiver Name")); SmtpClient mySmtpClient = new SmtpClient(); mySmtpClient.Send(myMessage); } When the Send method is called, the SmtpClient scans the Web.config file for a configured SMTP server or local drop folder. It then contacts that server and delivers the message or saves it locally.

27 Reading from Text Files The File Class in System.IO is available in.NET to be able to perform operation on files. File is a static class, so you don’t have to instantiate, you can call the methods directly. string myContents = System.IO.File.ReadAllText(@"C:\MyFile.txt"); Using the @ symbol tells the compiler that it should treat each backslash it finds as literal, ignoring the special meaning of the character.

28 File Class The following are common methods that allow you to work with a file

29 File Class Create a text file with some sample text in it and call it MyText.txt In the code behind of a page, add some code to read from the file using System.IO; // Provides access to the File class for reading the file using System.Net.Mail; // Provides access to the various mail related classes string fileName = Server.MapPath("~/App_Data/MyText.txt"); string fileContent = File.ReadAllText(fileName); Server.MapPath("~/App_Data/MyText.txt") returns a physical path such as C:\BegASPNET\Site\App_Data\MyText.txt. This code finds your MyText.txt file in the App_Data folder of your website and loads the contents of the file into a string object named fileContent.

30 Try it Out Pg. 303 Pg. 311 Pg. 315 Pg. 324 Pg. 328

31 Summary In this chapter we covered: What user input is and why it’s important to validate it What ASP.NET 4.5.1 has to offer to aid you in validating user input How to work with the built-in validation controls and how tocreate solutions that are not supported out of the box How to send e-mail using ASP.NET How to read text files


Download ppt "Chapter 9 Validating User Input. Objectives What user input is and why it’s important to validate it What ASP.NET 4.5.1 has to offer to aid you in validating."

Similar presentations


Ads by Google