Jquery Mask only alphabetical with strange behavior

Asked

Viewed 70 times

0

I am trying to add a mask in a field to accept only alphabetic characters.

Apparently I managed to find a solution.

Code

$(function () {

    $("#name").keypress( function(key) {

        if((key.charCode < 97 || key.charCode > 122) && (key.charCode < 65 || key.charCode > 90) && key.charCode != 32 ) {
            return false;
        }
    });
});

So far it works cool, accepts only letters([a-zA-Z]) and espaço only.

But the bizarre that after inserting any sequence of letters, after giving espaço twice appears a ponto out of nowhere.

If I try to explicitly forbid the permission of ponto including key.charCode == 46 in the if It takes everything and starts to accept any type of character.

Imagem com o bug

Does anyone have any idea how to make it work properly?

  • This condition will never be met: key.charCode < 65 && key.charCode > 90 I think here you wanted to use the or ||

  • True, I played it wrong and I didn’t see it

  • I just typed wrong even, I was looking at the screen of a pc and typing in another

1 answer

0


But what are you doing with this eventListener? You’re only returning false if the character isn’t what you want, what does that mean?

There is nothing to analyze in the code, the code posted is not even a mask. If you want to make a mask for letters and spaces, try something like:

$(function () {

    $("#name").on('input', function(e) {
        this.value = this.value.replace(/[^a-zà-ÿ\s]/ig, '');
    });

});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.