11.07.2015 Views

Improving Web Application Security: Threats and - CGISecurity

Improving Web Application Security: Threats and - CGISecurity

Improving Web Application Security: Threats and - CGISecurity

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 10: Building Secure ASP.NET Pages <strong>and</strong> Controls 267Date FieldsInput fields that have an equivalent .NET Framework type can be type checked bythe.NET Framework type system. For example, to validate a date, you can convertthe input value to a variable of type System.DateTime <strong>and</strong> h<strong>and</strong>le any resultingformat exceptions if the input data is not compatible, as follows.try{DateTime dt = DateTime.Parse(txtDate.Text).Date;}// If the type conversion fails, a FormatException is throwncatch( FormatException ex ){// Return invalid date message to caller}In addition to format <strong>and</strong> type checks, you might need to perform a range check on adate field. This is easily performed using the DateTime variable, as follows.// Exception h<strong>and</strong>ling is omitted for brevityDateTime dt = DateTime.Parse(txtDate.Text).Date;// The date must be today or earlierif ( dt > DateTime.Now.Date )throw new ArgumentException("Date must be in the past");Numeric FieldsIf you need to validate numeric data, for example, an age, perform type checks usingthe int type. To convert string input to integer form you can use Int32.Parse orConvert.ToIn32, <strong>and</strong> then h<strong>and</strong>le any FormatException that occurs with an invaliddata type, as follows:try{int i = Int32.Parse(txtAge.Text);. . .}catch( FormatException){. . .}

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!