jQuery and JavaScript cannot prevent XSS attacks. Period. However, we can make life a little bit harder for malicious users by escaping the markup entered in web forms or, more precisely, by turning special markup characters into SGML entities. Let's see how.
With a simple textarea like this:
<textarea id="text" rows="15" cols="15"></textarea>
we can bind a function to the keyup event that checks for the presence of special characters and replace them with their corresponding entities:
var checkText = function(element) {
element = $(element);
var text = element.val();
var re = /(>|<)+/g;
if(re.test(text)) {
element.val(text.replace(re, function($1) {
if($1 == '>') {
return '>';
} else {
return '<';
}
}));
}
};
Example:
$(function() {
var $text = $('#text');
$text.keyup(function() {
checkText(this);
});
});
You can see the demo below.