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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@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.
I think I would probably just do a second replacement myself, rather than try to modify that regex
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.