Enable TAB key for next field in Regexp

Asked

Viewed 620 times

0

Good morning, I am developing a form where I have a field "username", in this field I use this RegExp("^[0-9a-zA-Z \b]+$") , works perfectly, however at the time I use the TAB key to advance to the next field it does not work! I tried to use \t, but without success. Some dirt?

Follows code:

$('#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;
    }
});
  • 1

    Could you demonstrate how you are using this regex? by input pattern? mark, or even a function? this applied in a replace?

  • 1

    Could you post your code? Or a part of it?

  • I posted the code

  • 1

    Which browser are you using? What type of input is the user element? I tested your code here and it worked perfectly.

  • The browser is Firefox v44, well placed, I tested on Chrome and it really worked, the problem would be in Firefox?

  • The problem in 99% (not to say 100%) of cases is our code. Browsers have their differences and we have to make a code that suits everyone (or the most used).

Show 1 more comment

2 answers

1


I got something that worked for me.

$('#usuario').bind('keypress', function (event){
    var regex = new RegExp("^[0-9a-zA-Z \b\0]+$");
    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 generates the output that we expect t, but rather executes a change of element action. Then your output is null, the javascript escape to null is 0.

Maybe you hadn’t noticed, but your directional keys weren’t working either.

You deal by the key code, but I believe that treating all the keys that are necessary for the expected functioning will pollute your code.

Reference:

Javascript Regexp Reference

  • I tested with your code and it worked perfectly, great explanation helped me a lot; as you said, I hadn’t noticed that the directional ones didn’t work either! Thanks for the help

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

Browser other questions tagged

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