DataTable. How to stop a search.dt event from being fired from inside the event handler

I have this code, and when I detect the filter typed by the user contains some bad characters like ' I don’t want it to reach the Server.

I have this simplified code:

$table.on('search.dt', function () {
    var value = getValue();
    if (antiHackingHelper.isValid(value)) {
    } else { // Contains charakter like "'" so don't call the server with this bad filter
        // Don't send the request to the server with a filter with bad characters
    }
});

Answer

You cannot prevent the search from being performed at this point. search.dt is already broadcasted at the time your $table.on('search.dt' listener... is executed, and it is not part of a chain where you can cancel the search “upstream”.

Instead you could prevent illegal characters from being entered in the filter box in the first place :

var illegalChars = "',.-*)(";
$('.dataTables_filter input').on('keypress', function(e) {
   if (~illegalChars.indexOf(String.fromCharCode(e.keyCode))) {
     console.log('Illegal char entered, aborting');
     return false;
   }
})

demo -> http://jsfiddle.net/q39c3c0k/

Leave a Reply

Your email address will not be published. Required fields are marked *