Download presentation
Presentation is loading. Please wait.
Published byElyse Darr Modified over 10 years ago
1
CSCI 6962: Server-side Design and Programming Input Validation and Error Handling
2
Outline Overall goals of input validation Numeric inputs Regular expressions Dates and validation 2
3
Form Validation Detecting user error –Invalid form information –Inconsistencies of forms to other entities Enter ID not in database, etc. Correcting user error –Providing information or how to correct error –Reducing user memory load Preventing user error –Good instructions –Field types/values that prevent error –Error tolerance Example: Accepting phone numbers in multiple formats
4
Example 4 ValidationBean public String validate() { // Validate form elements // Return “valid” if all valid // Return “invalid” otherwise // and return to page
5
Error Pages Put error message next to source of error –Allows user to see where correction is needed
6
What to Validate Required fields have input –Text inputs non-empty Trim method useful to remove leading, trailing spaces name = name.trim(); if (name.equals(“”)) { … –Radio button groups and other lists have selection where required
7
Error Prevention Tell user what is required, optional Set default values where appropriate by setting initial values
8
Numeric Conversions in Java All values entered in text elements passed as string in request Must convert to numeric type before manipulating Methods built into Java static classes: int Integer.parseInt(String) for integer values double Double.parseDouble(String) for decimal values Example: int quantNum = Integer.parseInt(quantity); double cost = quantNum * 9.95; 8
9
Validating Numeric Inputs What if user enters non-numeric value? int quantNum = Integer.parseInt(quantity); Exception thrown in Java ValidateBean validate method Integer class parseInt method “five” NumberFormatException thrown Cannot parse “five”
10
Validating Numeric Inputs Unhandled exceptions cause error screen Must handle with try/catch block try { code which might cause exception … } catch (ExceptionType variable) { code to handle exception } code after block Jump here if exception Skip if no exception Set return value to forward to original or error page
11
Validating Numeric Inputs Jump here if NumberFormat exception due to quantity not being a number Skip if no exception Return to original page
12
Numeric Conversions in C# 12
13
Numeric Conversions in C# Similar exception handling format for non-numeric values: try { code that might cause exception } catch (exception type) { code to handle exception } 13
14
Numeric Error Prevention Avoid direct numeric input if possible Provide dropdowns that list values if possible Can use loop to generate array of SelectItem objects
15
Numeric Error Prevention Adding items to list using code (usually in Page_Load ): listname.Items.Add(new ListItem(string)) –Note: Only add elements to list in Page_Load if no elements already in list Otherwise, re-added every time page reloaded! Example: generating list of months using loop from 1 to 12
16
Validating Input Is numeric input valid? –Negative quantity invalid –What about quantity of 0? Is combination of choices legal? Is format of input legal? –Credit card number 15 or 16 digits –Phone number in correct format
17
Error Prevention Tell user if format or other rules apply
18
Regular Expressions Tool for verifying an input string is in a given format –Easier than parsing it yourself! Examples: –Credit card contains 16 digits –Phone number in form (3 digits) 3 digits - 4 digts –Email in form characters@characters.characterscharacters@characters.characters Note that correct format legal –Nonexistent phone number, etc. –Will need to verify against database
19
Regular Expressions Matching single characters a Matches character a. Matches any character [aeiou] Matches any character in list [^aeiou] Matches any character not in list [a-n] Matches any character in range a - n [a-d1-7] Matches any character in range a - n and 1 - 7
20
Regular Expressions Metacharacters match characters of a certain type –Note: the extra “\” in front is required by Java \\d Matches any digit 0-9 \\D Matches any non-digit \\w Matches “word” character a-z, A-Z, 0-9 \\W Matches any non-“word” character \\s Matches any “space” character (, tab, return) \\S Matches any non-“space” character
21
Regular Expressions Combining regular expressions Quantifiers give number of times a char must appear * Any number of times (including 0) + At least once {number} Exactly number times {num1, num2} Between num1 and num2 times XY Regex X and Y must occur in sequence X | Y Matches regex X or Y (X)(X) Used to group regular expressions
22
Regular Expressions Examples: –Credit card number: \\d{16} –Phone number: \\d{3}-\\d{3}-\\d{4} –Email address: \\w+@\\w+(\.\\w+)*
23
Regular Expressions in Java Java syntax: String.match(“regularexpression”) –Returns true if String is in form regularexpression
24
Regular Expressions in C# Construct Regex object from expression string Regex r = new Regex(@expression); –Need using System.Text.RegularExpressions; Match input string with Regex object if (r.IsMatch(input string)) {… 24
25
Error Tolerance Don’t reject based on format if any chance input valid –Example: other legal phone numbers 555-555-5555 (555) 555-5555 555.555.5555 … Choose most tolerant pattern to prevent false rejection –“Phone number is 10 digits separated by any number of non- digits” –Pattern: (\\d\\D*){10} digitAny number of non-digits 10 times
26
Dates and Validation Validity of user input may be related to current date Example: Credit card expiration date must not be before current month/year –Expiration year < current year invalid –Expiration year == current year and Expiration month < current month invalid Caution: –Date for user may be different from server Inaccurate clocks, international date boundary –Safest to only use for month, year 26
27
Calendar Dates in Java Construct a new GregorianCalendar object –Contains information about current date when created –Must import java.util.* library Use get(Calendar.fieldname) method to get component of that date –Field names = YEAR, MONTH, etc. –Returns an integer
28
Calendar Dates in Java Can use to generate values from current date Get current year Generate new SelectItem for each of the next 10 years
29
Calendar Dates in Java Can validate things about dates entered by user
30
Dates in ASP Key: DateTime object –DateTime.Now used to get current time/date –DateTime.Now.property gets specific values (Year, Month, Day, Hour, …)
31
Dates in ASP Example: Generating next 10 years starting with current year in Page_Load
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.