javascript input masking for numeric and english keyboard only

1.4k views Asked by At

I have an input field that has a masking of "999999999". It works perfectly fine on English keyboard but I am also able to enter Japanese/Chinese characters into it (breaking the masking).

Is there a way to restrict the input to english keyboard numerics only?

<input type="text" id="pin" lang="en">

I also tried the following but it did not work.

$.fn.onlyNumeric = function(config) {
    var defaults = {
    }
    var options = $.extend(defaults, config);
    return this.each(function(){
        $(this).bind('keyup blur', function(){
            $(this).val($(this).val().replace(/[^0-9]/g, ''));
        });
    });
}

$('#pin').onlyNumeric();

Any help?

2

There are 2 answers

0
Kei Minagawa On

I searched judging japanese character method for javascript in japanese. There is many japanese web site describing this. Sorry I don't know about jquery. I hope you may be able to get a hint in it. Here is a link I found.

http://javascript.eweb-design.com/1205_no.html

try sample page:

http://javascript.eweb-design.com/sample/s1205_1.html

I can't input japanese character in the input box on above sample page. It seems only [0-9] and [¥b] and ¥r char is allowed.

1
A. Wolff On

You could try to use keypress event like this:

$('#pin').on('keypress',function(e){
    if(!$.isNumeric(String.fromCharCode(e.which))) return false;
});

SEE DEMO