Reputation: 2623
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
.
Upvotes: 0
Views: 44
Reputation: 1707
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.
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.
Upvotes: 1
Reputation: 3436
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());
Upvotes: 0