Activate TAB key for next field in RegExp

0

Good morning, I'm developing a form where I have a "username" field, in this field I use this RegExp("^[0-9a-zA-Z \b]+$") , it works perfectly, however when I use the TAB key to move to the next field it does not work! I've already tried using \t , but to no avail. Any issues?

Follow the code below:

$('#usuario').bind('keypress', function (event){
    var regex = new RegExp("^[0-9a-zA-Z \b]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);

    if (!regex.test(key)){
        event.preventDefault();
        return false;
    }
});
    
asked by anonymous 15.03.2016 / 13:17

2 answers

1

I got something that worked for me.

$('#usuario').bind('keypress', function (event){
    var regex = new RegExp("^[0-9a-zA-Z \b
$('#usuario').bind('keypress', function (event){
    var regex = new RegExp("^[0-9a-zA-Z \b%pre%]+$");
    var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);

    if (!regex.test(key)){
    event.preventDefault();
    return false;
    }
});
]+$"); var key = String.fromCharCode(!event.charCode ? event.which : event.charCode); if (!regex.test(key)){ event.preventDefault(); return false; } });

Explanation:

You are testing with regex the output of the key you are pressing, but when you press the tab key on an HTML element, it was not generating the output that we expect \ t, but instead performs an element change action . So its output is null, the escape in javascript to null is \ 0.

Maybe you did not realize it, but your directional keys were not working either.

You deal with the key code, but I believe that handling all the keys that are necessary for the expected operation will pollute your code.

Reference:

JavaScript RegExp Reference

    
15.03.2016 / 17:38
1

Test Like This:

$('#usuario').bind('keypress', function (event){
    var regex = new RegExp("^[0-9a-zA-Z \b]+$");
    var keyCode = event.keyCode || event.which;

    // 9 é o keyCode do tab        
    if (!regex.test(String.fromCharCode(keyCode)) && keyCode != 9){ 
        event.preventDefault();
        return false;
    }
});
    
15.03.2016 / 16:11