简体   繁体   中英

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);
});

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: \\\\\\[\\]\\^\\/

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM