CSCI 6962: Server-side Design and Programming

Embed Size (px)


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

Text of CSCI 6962: Server-side Design and Programming

CSCI 6962

CSCI 6962: Server-side Design and ProgrammingInput Validation and Error Handling OutlineOverall goals of input validationNumeric inputsRegular expressionsDates and validation22Form ValidationDetecting user errorInvalid form information Inconsistencies of forms to other entitiesEnter ID not in database, etc.Correcting user errorProviding information or how to correct errorReducing user memory loadPreventing user errorGood instructionsField types/values that prevent errorError toleranceExample: Accepting phone numbers in multiple formats3


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

4Error PagesPut error message next to source of errorAllows user to see where correction is needed

5What to ValidateRequired fields have inputText inputs non-emptyTrim method useful to remove leading, trailing spacesname = name.trim();if (name.equals()) {

Radio button groups and other lists have selection where required

6Error PreventionTell user what is required, optional

Set default values where appropriate by settinginitial values

7Numeric Conversions in JavaAll values entered in text elements passed as string in requestMust convert to numeric type before manipulatingMethods built into Java static classes:int Integer.parseInt(String) for integer valuesdouble Double.parseDouble(String) for decimal valuesExample:int quantNum = Integer.parseInt(quantity);double cost = quantNum * 9.95;

88Validating Numeric InputsWhat if user enters non-numeric value?

int quantNum = Integer.parseInt(quantity);

Exception thrown in JavaValidateBean validate methodInteger class parseInt methodfiveNumberFormatException thrownCannot parse five

9Validating Numeric InputsUnhandled 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 exceptionSkip if noexceptionSet return value to forward to original or error page10

Validating Numeric InputsJump here if NumberFormat exception due to quantity not being a numberSkip if noexceptionReturn to original page11Numeric Conversions in C#12

12Numeric 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

13Numeric Error PreventionAvoid direct numeric input if possibleProvide dropdowns that list values if possible

Can use loop to generate array of SelectItem objects

14Numeric Error PreventionAdding 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 listOtherwise, re-added every time page reloaded!

Example: generating list of months using loop from 1 to 12

15Validating InputIs numeric input valid?Negative quantity invalidWhat about quantity of 0?

Is combination of choices legal?

Is format of input legal?Credit card number 15 or16 digitsPhone number in correct format

16Error PreventionTell user if format or other rules apply

17Regular ExpressionsTool for verifying an input string is in a given formatEasier than parsing it yourself!Examples:Credit card contains 16 digitsPhone number in form (3 digits) 3 digits - 4 digtsEmail in form characters@characters.characters

Note that correct format legalNonexistent phone number, etc.Will need to verify against database

18Regular ExpressionsMatching single characters

aMatches 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 - 719Regular ExpressionsMetacharacters match characters of a certain type

Note: the extra \ in front is required by Java\\dMatches any digit 0-9\\DMatches any non-digit\\wMatches word character a-z, A-Z, 0-9\\WMatches any non-word character\\sMatches any space character ( , tab, return)\\SMatches any non-space character20Regular ExpressionsCombining 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 timesXYRegex X and Y must occur in sequenceX | YMatches regex X or Y (X)Used to group regular expressions21Regular ExpressionsExamples:Credit card number: \\d{16} Phone number: \\d{3}-\\d{3}-\\d{4}Email address: \\w+@\\w+(\.\\w+)*

22Regular Expressions in JavaJava syntax: String.match(regularexpression)Returns true if String is in form regularexpression

23Regular 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

24Error ToleranceDont reject based on format if any chance input validExample: other legal phone numbers555-555-5555(555) 555-5555555.555.5555Choose most tolerant pattern to prevent false rejectionPhone number is 10 digits separated by any number of non-digitsPattern: (\\d\\D*){10}digitAny number of non-digits10 times25Dates and ValidationValidity of user input may be related to current dateExample: Credit card expiration date must not be before current month/yearExpiration year < current year invalidExpiration year == current year and Expiration month < current month invalid

Caution:Date for user may be different from serverInaccurate clocks, international date boundarySafest to only use for month, year

2626Calendar Dates in JavaConstruct a new GregorianCalendar objectContains information about current date when createdMust import java.util.* libraryUse get(Calendar.fieldname) method to get component of that date Field names = YEAR, MONTH, etc.Returns an integer

27Calendar Dates in JavaCan use to generate values from current date

Get current yearGenerate new SelectItem for each of the next 10 years28Calendar Dates in JavaCan validate things about dates entered by user

29Dates in ASPKey: DateTime object DateTime.Now used to get current time/ gets specific values(Year, Month, Day, Hour, )


Dates in ASPExample: Generating next 10 years starting with current year in Page_Load31