hadi karami
hadi karami

Reputation: 13

regex not work correctly on keypress

I want to prevent users from using letter keys on input and i use following code in jquery

var enK = /^(6[5-9])|([7-9][0-9])|(1([01][0-9]|2[0-2]))$/y;
// this regex is for event code of a-z and A-Z letters in keypress event
$(document).ready(function(){
    $('input').bind('keypress',function(evt){
        var evC = evt.which || evt.charCode;
        if(enK.test(evC)){
            event.preventDefault();
        }
    })
});

Test1 :

Input keys : abcdefg

Output : bdf

Test2 :

Input keys : aaaaaa

Output : aaa

These tests means that :

-First keypress is prevented

-Second keypress not match to regex and will not prevented

-Third keypress is prevented

-Fourth keypress not match to regex and will not prevented

...

following code has same resualt.

var enC = /[a-z|A-Z]/g;
$(document).ready(function(){
    $('input').bind('keypress',function(evt){
        var evC =  evt.which || evt.charCode;
        evC = String.fromCharCode(evC);
        if(enC.test(evC)){
            event.preventDefault();
        }
    })
});

Now how should i solve this problem? thanks.

Upvotes: 0

Views: 3027

Answers (1)

Jorg
Jorg

Reputation: 7250

$(document).ready(function(){
  $('input').bind('keypress',function(evt){
    var key = String.fromCharCode(evt.which || evt.charCode);
    if(/[a-z]/i.test(key) === false) evt.preventDefault();
  })
});

This prevents all input except a-z and A-Z.

https://jsfiddle.net/0b2f7wyL/1/

@fubar in the comments had the right answer: the y is the 'Sticky' flag, it tells the regular expression to look for a match at lastIndex and only at lastIndex (not earlier or later in the string), which is why ever other check failed.

Upvotes: 2

Related Questions