khinkle
khinkle

Reputation: 111

Can I use asp.net validators on user input to avoid sql injection attacks?

I am designing a web site where the user specifies an account ID (must be 8 digits, exactly) in order to look up Billing Dates associated with that account. I have used an asp.net regex validator to prevent the user from entering characters. I have also attached a required field validator to this text box.

I have read up on SQL Injection attacks from other stackoverflow questions, but I have not come across anything relating to protecting queries with validators.

With these validators set, is there any reason for me to worry about sql injection attacks? Is there anything else I need to (or should) do to prevent a malignant user from abusing this user input.

Here is my C# code for the SQL query and populating a drop down list with the bill cycle dates associated with the AccountID:

string sqlCommandString = "SELECT StatementDate AS StateDate FROM dbTable " + 
    "WHERE AccountID = '" + AccountID + "' ORDER BY StatementDate DESC";

string ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
using (SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection))
{
    sqlConnection.Open();
    DropDownList_StatementDate.DataSource = sqlCommand.ExecuteReader();
    DropDownList_StatementDate.DataBind();
}

And here is the regex validator I used:

<asp:RegularExpressionValidator
    ID="RegExpVal_AccountID"
    runat="server"
    ErrorMessage="Must be 8 digits"
    ValidationExpression="^\d{8}$"
    ControlToValidate="TextBox_AccountID"
    CssClass="ValidatorStyle"
    Display="Dynamic">        
</asp:RegularExpressionValidator>

Thank you.

Upvotes: 2

Views: 1869

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039110

Simply use parametrized queries (the only safe way to prevent SQL injection attacks):

string sqlCommandString = "SELECT StatementDate AS StateDate FROM dbTable " + 
    "WHERE AccountID = @AccountID ORDER BY StatementDate DESC";

string ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

using (SqlConnection sqlConnection = new SqlConnection(ConnectionString))
using (SqlCommand sqlCommand = new SqlCommand(sqlCommandString, sqlConnection))
{
    sqlConnection.Open();
    sqlCommand.Parameters.AddWithValue("@AccountID", AccountID);
    DropDownList_StatementDate.DataSource = sqlCommand.ExecuteReader();
    DropDownList_StatementDate.DataBind();
}

Upvotes: 12

Related Questions