0

I have an input field and I want to do a validation check that will prevent users from subitting SQL injection-like strings. How would this be done in JavaScript?

var userInput = '"SELECT * FROM Users WHERE UserId = " + txtUserId;'
var arrayCheck = [SELECT, FROM, WHERE];

So now I need to check userInput for the number of matches in the array arrayCheck.

If the number of matches is three or higher, return false, otherwise return true.

1
  • 1
    This is not a proper way! Will disturb UX.. Something like mysqli_real_escape_string will help! What if user want to input as "WHERE is the mall? I want to SELECT 10 shirts FROM there" Commented Apr 22, 2016 at 8:04

2 Answers 2

1

You can search for Strings in Strings using

var stringVar = 'test';
var x = stringVar.indexOf('test') > -1;

Basically, indexOf will return the index of the starting position of a string in a string, if it cant find it will return -1.

reference

So for your problem you could so something like so.

function testForSQLKeyWords(inputText) {
  var keywords = ['SELECT', 'FROM', 'WHERE'];
  var threshold = 3;
  var hits = 0;
  for (var i = 0; i < keywords.length; i++) {
    var keyword = keywords[i];
    if (inputText.indexOf(keyword) > -1) {
      hits++;
    }
  }
  return hits >= threshold;
}

//Then call it

var inputText = 'SELECT name FROM people';

testForSQLKeyWords(inputText);

May I also suggest thinking about maybe using .toLowerCase reference.

Sign up to request clarification or add additional context in comments.

2 Comments

What about for multiple string occurences?
improved my answer
0

You could filter all your arrayCheck words and then count them, checking against the string:

var matches = arrayCheck.filter(function(item){
   return userInput.indexOf(item) > -1;
});
var numberOfMatches = matches.length;
if(numberOfMatches >= 3)
    //do your thing

Be careful, you could not match the words because of cases, i would recommend to lowercase or uppercase the entire string. Inside the filter:

return userInput.toLowerCase().indexOf(item.toLowerCase());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.