How to block double character input in the event "onkeydown"

0

I was trying to make a simple, small code to validate input of type text . For this I have used an event onkeydown in input where it returns false or true, ex: onkeydown="return somenteLetras()" ; in the JavaScript code, by triggering this function, it captures the keycode of the key typed and, depending on its code, it returns false or true allowing only letters to return true, at least in theory. The problem was when I realized that even if a key is locked, it allows it to enter it since before the key is pressed an accent is typed, for example: if in the function I only allow the input of the letter a , I type b , keycode will be different and then it will block the input of b , but if I type any accent before then enter b , it blocks the accent but allows b p>

Follow the code to understand it better:

HTML

<input type="text" onkeydown="return letraA()">

JS

function letraA() {
   var kc = event.which || event.KeyCode;
   if(kc == 65) {
       return true;
   }
   return false;
}

In this code it only allows the letter a , but if you hit the ´ key and then a b , for example, instead of blocking ´b it only blocks the accent and lets pass the b . I wanted to know how to resolve this.

    
asked by anonymous 26.05.2017 / 23:48

1 answer

0

I do not know if this will help, but if you just need to sanitize (and not prevent from being typed), you can use another way to do that.

First switch from keydown to keyup, so the function will be executed when the key is released.

Then use the .replace() function to remove all the characters you do not want.

Getting like this ..

<script>
    window.onload = function()
    {
        document.getElementById('input-a').addEventListener('keyup', function(e)
        {
            this.value = this.value.replace(/[^Aa]/g, '');
        });
    };
</script>
<input type="text" id='input-a'>

If you only want letters and space, simply adapt your regular expression.

<script>
    window.onload = function()
    {
        document.getElementById('input-a').addEventListener('keyup', function(e)
        {
            this.value = this.value.replace(/[^A-Za-z ]/g, '');
        });
    };
</script>
<input type="text" id='input-a'>

It's easier to remove what was typed than to try to block keys like this.

window.onload indicates that the code will run as soon as the window loads, it is equivalent to $(document).ready() of jQuery.

Remember that if you are working with a server, never discard server-side validation, which is of the utmost importance, as any client-side validation can be circumvented.

    
27.05.2017 / 01:01