CSCI 6962: Server-side Design and Programming Input Validation and Error Handling Outline • • • • Overall goals of input validation Numeric inputs Regular expressions Dates and validation 2 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 Example ValidationBean public String validate() { // Validate form elements // Return “valid” if all valid // Return “invalid” otherwise // and return to page 4 Error Pages • Put error message next to source of error – Allows user to see where correction is needed 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 Error Prevention • Tell user what is required, optional • Set default values where appropriate by setting initial values 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 Validating Numeric Inputs • What if user enters non-numeric value? int quantNum = Integer.parseInt(quantity); Cannot parse “five” • Exception thrown in Java “five” ValidateBean validate method Integer class NumberFormatException parseInt method thrown Validating Numeric Inputs • Unhandled exceptions cause error screen • Must handle with try/catch block try { code which might cause exception … Jump here if } exception catch (ExceptionType variable) { Skip if no code to handle exception exception } code after block Set return value to forward to original or error page Validating Numeric Inputs Jump here if NumberFormat exception due to quantity not being a number Return to original page Skip if no exception Numeric Conversions in C# 12 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 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 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 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 Error Prevention • Tell user if format or other rules apply 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.characters • Note that correct format legal – Nonexistent phone number, etc. – Will need to verify against database Regular Expressions • Matching single characters a . [aeiou] [^aeiou] [a-n] [a-d1-7] Matches character a Matches any character Matches any character in list Matches any character not in list Matches any character in range a - n Matches any character in range a - n and 1 - 7 Regular Expressions • Metacharacters match characters of a certain type \\d \\D \\w \\W \\s \\S Matches any digit 0-9 Matches any non-digit Matches “word” character a-z, A-Z, 0-9 Matches any non-“word” character Matches any “space” character ( , tab, return) Matches any non-“space” character – Note: the extra “\” in front is required by Java Regular Expressions • Combining regular expressions XY X|Y (X) Regex X and Y must occur in sequence Matches regex X or Y Used to group regular expressions • Quantifiers give number of times a char must appear * + {number} {num1, num2} Any number of times (including 0) At least once Exactly number times Between num1 and num2 times Regular Expressions • Examples: – Credit card number: \\d{16} – Phone number: \\d{3}-\\d{3}-\\d{4} – Email address: \\w+@\\w+(\.\\w+)* Regular Expressions in Java • Java syntax: String.match(“regularexpression”) – Returns true if String is in form regularexpression 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 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 nondigits” – Pattern: (\\d\\D*){10} digit Any number of non-digits 10 times 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 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 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 Calendar Dates in Java • Can validate things about dates entered by user Dates in ASP • Key: DateTime object – DateTime.Now used to get current time/date – DateTime.Now.property gets specific values (Year, Month, Day, Hour, …) Dates in ASP • Example: Generating next 10 years starting with current year in Page_Load