CSCI 6962: Server-side Design and Programming Java Server Faces Scoping and Session Handling.
CSCI 6962: Server-side Design and Programming Input Validation and Error Handling.
-
Upload
elyse-darr -
Category
Documents
-
view
228 -
download
0
Transcript of 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
4
ValidationBean
public String validate() { // Validate form elements // Return “valid” if all valid // Return “invalid” otherwise // and return to page
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 spacesname = 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 settinginitial 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 valuesdouble 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);
• Exception thrown in Java
ValidateBean validate method
Integer class parseInt method
“five”
NumberFormatException thrown
Cannot parse “five”
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 noexception
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
Skip if noexception
Return to original page
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
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 [email protected]
• Note that correct format legal– Nonexistent phone number, etc.– Will need to verify against database
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
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
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) Used to group regular expressions
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 stringRegex r = new Regex(@expression);– Need using System.Text.RegularExpressions;
• Match input string with Regex objectif (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 non-
digits”– 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
Dates in ASP
• Key: DateTime object – DateTime.Now used to get current time/date– DateTime.Now.property gets specific values
(Year, Month, Day, Hour, …)