Question

Let's assume I have an <input> tag. Value of this tag is used on change. The problem is that if a user inputs single or double quotation marks - it breaks the code. Right now this is solved quite simple:

  1. Override keypress for these keys;
  2. Forbid paste to input.

Here is the sample Code:

HTML

<input id="TestInput"></input>

Javascript

$("#TestInput").keypress(function (e) { // override keypress of " or '
    if (e.which == 13 || e.which == 34 || e.which == 39) {
        return false;
    }
})

.bind("paste", function (e) {// forbid paste
    e.preventDefault();
})

.change(function(){
 var value = $(this).val();
    //and then I use this value for my operations
});

Sample Fiddle

The question: is there a better way to get rid of all quotation marks without forbiding paste?

Note: I assume it can be solved with RegExp, but I'm no good with them, so if you can provide a Regexp - this could work.

Thanks everyone in Advance.

Update-1

On change an ajax call is performed to a method which call the DB and quotes break the query somehow like this: query:

var query = "SELECT Column FROM table WHERE somecolumn LIKE '" + inputVal+ "'%";

if inputVal is something like "foo the resulting sting will look like:

var query = "SELECT Column FROM table WHERE somecolumn LIKE '" + "foo+ "'%";

which obviously breaks the query. + there are no items in the Database which contain quotes.

Was it helpful?

Solution

Only handle the data in the textbox:

$("#TestInput").on('input', function () {
    var value = $(this).val().replace(/'/g, '').replace(/"/g, '');
    // go on with processing data
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top