Andres SK
Andres SK

Reputation: 10974

jQuery input filter for textarea

I adapted this solution into my script. The idea is to prevent the user from typing unauthorized characters (of course there is also a filter on the back end).

$('#someinput').keyup(function() {
    var $th = $(this);
    $th.val( $th.val().replace(/[^a-zA-Z0-9]/g, function(str) {
        console.log(str);
        return '';
    }))
})

It works nice, but I also need the users to be able to type specific allowed characters like: .,!?ñáéíóú - I mean, the basic a-zA-Z0-9 plus some basic chars and the whole bunch of special language characters.

What actually needs to be left out are: @#$%^&*()=_+"':;/<>\|{}[]

Any ideas? Thanks!

Solution thanks to Michael

//query
$('#someinput').keyup(function() {
    var $th = $(this);
    $th.val($th.val().replace(/[@#$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
}).bind('paste',function(e) {
    setTimeout(function() {
        $('#someinput').val($('#someinput').val().replace(/[@#$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g,function(str){return '';}));
        $('#someinput').val($('#someinput').val().replace(/\s+/g,' '));
    },100);
});

Upvotes: 3

Views: 4606

Answers (2)

Michael Berkowski
Michael Berkowski

Reputation: 270617

Invert your regular expression to only replace the specific characters you want omitted:

$th.val( $th.val().replace(/\s?[@#$%\^&*()=_+"':;\/<>\\\|{}\[\]]/g, ""));
// Edit: added optional \s to replace spaces after special chars

Note, a few of them need to be escaped with a backslash inside a [] character class: \\\[\]\^\/

Upvotes: 5

Groovetrain
Groovetrain

Reputation: 3325

If I'm understanding what you are wanting to do, can't you just add those unwanted characters to your regex instead of doing the [^a-zA-Z0-9]?

Replace that with [@#\$%\^&\*\(\)=_\+"':;\/<>\\\|\{\}\[\]] (notice the escaping)

Upvotes: 3

Related Questions