Return to
HomePage
ASPNET2SecurityFAQs


Question: How do I validate input in server-side controls?

Answer:

You can use the ASP.NET validator controls, such as the RegularExpressionValidator, RangeValidator and CustomValidator, to validate and constrain input in server side controls.
Regular expressions are a good way to validate text fields such as names, addresses, phone numbers, and other user information. If inputs are not validated appropriately it makes your application vulnerable to injection attacks like SQL Injection and Cross-Site Scripting.
Here is a sample of a RegularExpressionValidator control to validate a name field
		 <form id="WebForm" method="post" runat="server">
		   [<asp:TextBox] id="txtName" runat="server"></asp:TextBox>
		   [<asp:RegularExpressionValidator] id="nameRegex"runat="server" ControlToValidate="txtName"  ValidationExpression="[a-zA-Z'.`-´\s]{1,40}" ErrorMessage="Invalid name">
		   </asp:regularexpressionvalidator>
		 </form>
	
The validation expression constrains the input name field to alphabetic characters (lowercase and uppercase), the single apostrophe for names such as O’Dell, and the dot character. In addition, the field length is constrained to 40 characters.
The validation controls use client-side script to perform validation on the client browser (if supported by the browser), and also run validation logic on the server after data is posted back.

More Information

For more information on validating server-side controls and HTML controls in ASP.NET, see “How To: Protect from Injection attacks in ASP.NET” at http://msdn.microsoft.com/library/en-us/dnpag2/html/paght000003.asp and "How To: Use Regular expressions to constrain input in ASP.NET" http://msdn.microsoft.com/library/en-us/dnpag2/html/paght000001.asp


Return to
HomePage
ASPNET2SecurityFAQs
Microsoft Communities