Validate input parameters

From Guidance Share

Jump to: navigation, search

- J.D. Meier, Alex Mackman, Michael Dunner, Srinath Vasireddy, Ray Escamilla and Anandha Murukan

Validate all input parameters that come from form fields, query strings, cookies, and HTTP headers. The System.Text.RegularExpressions.Regex class helps validate input parameters. For example, the following code shows how to use this class to validate a name passed through a query string parameter. The same technique can be used to validate other forms of input parameter, for example, from cookies or form fields. For example, to validate a cookie parameter, use Request.Cookies instead of Request.QueryString.

using System.Text.RegularExpressions;
. . .
private void Page_Load(object sender, System.EventArgs e)
{
 // Name must contain between 1 and 40 alphanumeric characters
 // together with (optionally) special characters '`´ for names such
 // as D'Angelo
 if (!Regex.IsMatch(Request.QueryString["name"], 
                    @"^[a-zA-Z'`-´\s]{1,40}$"))
   throw new Exception("Invalid name parameter");
 // Use individual regular expressions to validate all other
 // query string parameters
 . . .
}

For more information about using regular expressions and how to validate input data, see "Input Validation" at http://msdn.microsoft.com/library/en-us/dnnetsec/html/THCMCh10.asp?frame=true#c10618429_006 .

References

Personal tools