哪种方法可以过滤文本字段的数值? [英] 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();
});
这是相当明确的,但转向(在所有浏览器的最新版本中)Firefox将使这个还可以使用箭头键和删除/退格键来防止移动,而其他浏览器则不会。
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.
环顾四周我发现我还需要检查这些键,并检查 e
事件参考中公开的不同属性。
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.
我做错了什么?在这种验证方面哪个是最佳做法?
推荐答案
我们会回复两个按键,和模糊事件。当某人按下某个键时,我们会检查输入的密钥是否为数字。如果是,我们允许。否则,我们会阻止它。
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].+/, "");
});
演示: http://jsfiddle.net/jonathansampson/S7VhV/5/
这篇关于哪种方法可以过滤文本字段的数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!