views:

32

answers:

3

I have a form set up where users can enter their booking for a room at my college. I want to validate the user input to avoid SQL injection (my program uses a MS Access database) and also stop numbers and synbols in their name, etc.

I can do the validation fine, but there is to be a lot of validation and then methods executed only if all validation tests come back as true. I did have something like this:

If txtName.Text = "" Then
    frmBookErr.SetError(txtName, "Name field cannot be left blank.")
    fail = 1
Else
    frmBookErr.SetError(txtName, "")
    fail = 0
End If

And then check the fail variable, but it obviously gets overridden later in the form if one of the validation tests come back as true.

Can anyone provide some input into this? Thanks.

A: 

If you want to avoid SQL injection, use parameterised SQL queries or stored procedures, and do not construct SQL by concatenation.

David M
A: 

To avoid SQL Injections you need to use something that doesn't directly allow for changes in the SQL Query.

Now this doesn't mean you cant provide values, it means that you strongly specifies what types you want to process to the server.

Example from CodeProject

string commandText = "SELECT * FROM Customers "+
    "WHERE Country=@CountryName";
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.Parameters.Add("@CountryName",countryName);

Instead of providing the countrName as concated string, you actually tell your Sql Command that you provide it as a parameter, which wont allow for any changes in the query itself.

Filip Ekberg
+1  A: 

Set your fail variable at the start of the procedure to 0 then only set it to 1 if something fails...

    fail = 0
    If txtName.Text = "" Then
        frmBookErr.SetError(txtName, "Name field cannot be left blank.")
        fail = 1
    End If
    If txtSomethingElse.Text = String.Empty Then fail = 1
    If fail = 0 Then frmBookErr.Clear()
Walter