Sunny Gupta
Sunny Gupta

Reputation: 7067

Field validation for a jsp-form

I have a jsp-form with field named Description. This field declared as follows

<input type="text" name="description">

This value used to compose SQL query:

select * from Engines where description like '% (Value from the field)%'

When a user enters alphanumeric characters it works fine, but it fails when user enters special characters, like single quote symbol: '

My questions:

  1. How can I deal with this on the server-side
  2. If it is necessary to implement on JavaScript, then what characters have to be filtered out?

Thank you.

Upvotes: 0

Views: 1782

Answers (4)

SurinderBhomra
SurinderBhomra

Reputation: 2199

You could remove the invalid characters through basic validation using JavaScript and Regex:

<script type="text/javascript">
var str= document.getElementById('mySearch').value;
str=str.replace(/[^A-Za-z0-9]/g,'');
alert(str);
</script>

But I agree with hkutluay, parametrized queries would be the better route.

Upvotes: 0

user784540
user784540

Reputation:

Use prepared statement instead of composing SQL query string. Your way is vulnerable to SQL Injection attack.

If it is not possible to use PreparedStatements, then use java regular expression to remove special chars before passing this field value to SQL query.

There is a post related to this task.

Do not use javascript to filter out special symbols. It won't protect you from sql-injection attack. An attacker may forge his own form without validation javascript and attack your server.

Upvotes: 3

Frantisek Kossuth
Frantisek Kossuth

Reputation: 3524

What you do is considered a very bad practice and may result in very bad things... http://en.wikipedia.org/wiki/SQL_injection

Upvotes: 0

hkutluay
hkutluay

Reputation: 6944

Use parameterized query for handle this kind of problems.

Upvotes: 1

Related Questions