3

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);
});
Community
  • 1
  • 1
Andres SK
  • 10,779
  • 25
  • 90
  • 152
  • 1
    http://stackoverflow.com/questions/6565480/javascript-jquery-regex-replace-input-field-with-valid-characters see if this helps – Val Dec 08 '11 at 14:55

2 Answers2

5

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

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390
  • great! i also added this to the bind('paste'),function(e) to run the regex when the user pastes a bunch of text. if he pastes: "hello @ friend" the result will be "hello friend" that is ok excepto that there are 2 spaces instead of one. is it possible to prevent more than one space in the same regex? or should i place it in a separate regex for the bind() event only. – Andres SK Dec 08 '11 at 15:05
  • @andufo you can put an optional space before & after the `[]` above. Try my edit above and see if it works for you. Otherwise, you can just do another replacement to collapse multiple spaces: `/\s+/` replace with one space. – Michael Berkowski Dec 08 '11 at 15:10
  • I think I would probably just do a second replacement myself, rather than try to modify that regex – Michael Berkowski Dec 08 '11 at 15:11
3

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)

Groovetrain
  • 3,315
  • 19
  • 23