MSDN Library

Validating User Input 

When constructing an application that accesses data, you should assume all user input to be malicious until proven otherwise. Failure to do so can leave your application vulnerable to attack. The .NET Framework contains classes to help you enforce a domain of values for input controls, such as limiting the number of characters that can be entered, and provides event hooks for writing code to check the validity of values. Data can be validated and strongly typed, as discussed in Mapping .NET Framework Data Provider Data Types to .NET Framework Data Types. In addition, the .NET Framework contains classes to help you evaluate string data from input controls.

Using Regular Expressions

The Regex class can be used to check the validity of user input in your applications by validating user input against a particular pattern. In addition, code can use regular expressions to transform invalid text into valid text. The CleanInput method defined here takes an input string and strips all non-alphanumeric characters except the following:

String CleanInput(string strIn)
    // Replace invalid characters with empty strings.
    return Regex.Replace(strIn, @"[^\w\.@-]", ""); 

.NET Framework Regular Expressions has links to additional samples that illustrate the use of the Regex class to validate user input.

ASP.NET Validation Controls

An important aspect of creating secure ASP.NET applications is being able to validate the information users enter on a form. ASP.NET has validation controls that provide an easy-to-use and powerful way to check for errors and, if necessary, display messages to the user. You can find links to validation control topics in Validating User Input in ASP.NET Web Pages and Validation Controls.

Validating User Input in SQL Server Stored Procedures

Validating user input in client code is important so that you do not waste round trips to the server. It is equally important to validate parameters to stored procedures on the server to catch invalid input that bypasses client-side validation. For SQL Server 2000, see "Validating User Input", "Specifying Parameters", "Stored Procedures", and "CREATE PROCEDURE" in SQL Server 2000 Books Online. For SQL Server 2005, see "Stored Procedures (Database Engine)" and subordinate topics in SQL Server 2005 Books Online.

See Also

© 2016 Microsoft