31
CSCI 6962: Server-side Design and Programming Input Validation and Error Handling

CSCI 6962: Server-side Design and Programming

  • Upload
    ismail

  • View
    27

  • Download
    1

Embed Size (px)

DESCRIPTION

CSCI 6962: Server-side Design and Programming. Input Validation and Error Handling . Form Validation. Detecting user error Invalid form information Inconsistencies of forms to other entities Enter ID not in database, etc. Correcting user error - PowerPoint PPT Presentation

Citation preview

Page 1: CSCI 6962:  Server-side Design and Programming

CSCI 6962: Server-side Design and Programming

Input Validation and Error Handling

Page 2: CSCI 6962:  Server-side Design and Programming

Outline

• Overall goals of input validation• Numeric inputs• Regular expressions• Dates and validation

2

Page 3: CSCI 6962:  Server-side Design and Programming

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

Page 4: CSCI 6962:  Server-side Design and Programming

Example

4

ValidationBean

public String validate() { // Validate form elements // Return “valid” if all valid // Return “invalid” otherwise // and return to page

Page 5: CSCI 6962:  Server-side Design and Programming

Error Pages• Put error message next to source of error

– Allows user to see where correction is needed

Page 6: CSCI 6962:  Server-side Design and Programming

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

Page 7: CSCI 6962:  Server-side Design and Programming

Error Prevention

• Tell user what is required, optional

• Set default values where appropriate by settinginitial values

Page 8: CSCI 6962:  Server-side Design and Programming

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

Page 9: CSCI 6962:  Server-side Design and Programming

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”

Page 10: CSCI 6962:  Server-side Design and Programming

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

Page 11: CSCI 6962:  Server-side Design and Programming

Validating Numeric Inputs

Jump here if NumberFormat exception due to quantity not being a number

Skip if noexception

Return to original page

Page 12: CSCI 6962:  Server-side Design and Programming

Numeric Conversions in C#

12

Page 13: CSCI 6962:  Server-side Design and Programming

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

Page 14: CSCI 6962:  Server-side Design and Programming

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

Page 15: CSCI 6962:  Server-side Design and Programming

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

Page 16: CSCI 6962:  Server-side Design and Programming

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

Page 17: CSCI 6962:  Server-side Design and Programming

Error Prevention• Tell user if format or other rules apply

Page 18: CSCI 6962:  Server-side Design and Programming

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

Page 19: CSCI 6962:  Server-side Design and Programming

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

Page 20: CSCI 6962:  Server-side Design and Programming

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

Page 21: CSCI 6962:  Server-side Design and Programming

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

Page 22: CSCI 6962:  Server-side Design and Programming

Regular Expressions

• Examples:– Credit card number: \\d{16} – Phone number: \\d{3}-\\d{3}-\\d{4}– Email address: \\w+@\\w+(\.\\w+)*

Page 23: CSCI 6962:  Server-side Design and Programming

Regular Expressions in Java• Java syntax: String.match(“regularexpression”)

– Returns true if String is in form regularexpression

Page 24: CSCI 6962:  Server-side Design and Programming

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

Page 25: CSCI 6962:  Server-side Design and Programming

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

Page 26: CSCI 6962:  Server-side Design and Programming

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

Page 27: CSCI 6962:  Server-side Design and Programming

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

Page 28: CSCI 6962:  Server-side Design and Programming

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

Page 29: CSCI 6962:  Server-side Design and Programming

Calendar Dates in Java• Can validate things about dates entered by user

Page 30: CSCI 6962:  Server-side Design and Programming

Dates in ASP

• Key: DateTime object – DateTime.Now used to get current time/date– DateTime.Now.property gets specific values

(Year, Month, Day, Hour, …)

Page 31: CSCI 6962:  Server-side Design and Programming

Dates in ASP

• Example: Generating next 10 years starting with current year in Page_Load