Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

javascript - Which is the proper way of filtering numeric values for a text field?

I'm working on a textfield working with the kind of validation that wouldn't let you enter other than numeric values. As so, my initial code looked quite simple and similar to this:

$(textField).onKeyPress(function(e) {
    if (e.which < 48 && e.which > 57)
        e.preventDefault();
});

This is fairly strightforward, but turns that (in the latest version of all browsers) Firefox will make this also prevent movement with the arrow keys and delete/backspace keys, whereas the other browsers would not.

Looking around I found that I would need to also check for these keys, and check for different properties exposed in the e event reference.

My final code looks something like this:

$(textField).onKeyPress(function(e) {
    var code = e.which || e.keyCode;
    if (code > 31  // is not a control key
        && (code < 37 || code > 40) // is not an arrow key
        && (code < 48 || code > 57) // is not numeric
        && (code != 46) // is not the delete key
    )
        e.preventDefault();
});

However, this feels to be too much to solve a fairly simple problem as just preventing non-numeric.

What am I doing wrong? Which is the best practice in terms of this kind of validation?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

We'll respond to both keypresses, and the blur event. When somebody press a key, we check to see if the key entered is a number. If it is, we permit it. Otherwise, we prevent it.

If the field is blurred, we remove any non-numerical values, and all those values that follow. This will prevent the user from pasting in non-numerical strings:

$("#textfield").on("keypress blur", function(e){
    if ( e.type === "keypress" )
        return !!String.fromCharCode(e.which).match(/^d$/);
    this.value = this.value.replace(/[^d].+/, "");
});

Demo: http://jsfiddle.net/jonathansampson/S7VhV/5/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...