双/浮点数的 jQuery 输入验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1542380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery input validation for double/float
提问by k0ni
What's the best method to mask an input field to only allow float/double, without any jquery plugin.
什么是屏蔽输入字段以仅允许浮点/双精度,而没有任何 jquery 插件的最佳方法。
Acutally i'm doing it like this:
实际上我是这样做的:
$("#defaultvalue").bind("keypress", function(e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
});
but thats only for numbers thx
但这仅适用于数字 thx
采纳答案by Daff
JavaScripts parseFloat()function returns NaN, when your input is not a number. For i18n you will probably have to replace the floating point separator (e.g. , with .)
当您的输入不是数字时,JavaScript 的parseFloat()函数返回 NaN。对于 i18n,您可能必须替换浮点分隔符(例如,用 .)
回答by jms301
parseFloat(value) and value.match('^[0-9]*\.[0-9]*$')
I guess you could drop the parseFloat and just use the regex.
我想你可以删除 parseFloat 并只使用正则表达式。
回答by Weslei
In HTML page just call JS SetFloatEntry Method.
在 HTML 页面中只需调用 JS SetFloatEntry 方法。
Example:
例子:
<html>
<script>
$(document).ready(function () {
SetFloatEntry("weight");
});
</script>
<body>
<input id="weight" type="text" />
</body>
</html>
Put this on your JS refered file:
把它放在你的 JS 引用文件上:
/* Main function */
function SetFloatEntry(fieldName) {
$("#" + fieldName).keydown(function (event) {
return NumericField($("#" + fieldName).val(), event, true);
});
}
/* Auxiliar */
var strUserAgent = navigator.userAgent.toLowerCase();
var isIE = strUserAgent.indexOf('msie') > -1;
var reKeyboardChars = /[\x03\x08\x09\x0D\x16\x18\x1A\x2E\x23\x24\x25\x26\x27\x28\x2D]/;
var reNumber = /^((\d{1,3}\.)*\d{3}|\d*,{0,1}\d+|(\d{1,3}\.)*\d{3},{0,1}\d+|\d*)$/;
function NumericField(str, objEvent, isFloat) {
oldValue = str;
strKey = GetChar(objEvent);
if (((objEvent.which) ? objEvent.which : event.keyCode) == 13
|| (((objEvent.which) ? objEvent.which : event.keyCode) == 190 && isFloat))
return true;
if (!KeyNumber(objEvent)
&& !reKeyboardChars.test(strKey)
&& !(objEvent.ctrlKey
&& reClipboard.test(strKey)))
return false;
return true;
}
function KeyNumber(objEvent) {
return reNumber.test(GetChar(objEvent));
}
function GetChar(objEvent) {
var arrKeys = new Array();
arrKeys[96] = '0';
arrKeys[97] = '1';
arrKeys[98] = '2';
arrKeys[99] = '3';
arrKeys[100] = '4';
arrKeys[101] = '5';
arrKeys[102] = '6';
arrKeys[103] = '7';
arrKeys[104] = '8';
arrKeys[105] = '9';
arrKeys[111] = '/';
arrKeys[193] = '/';
iKeyCode = GetKeyCode(objEvent);
if (arrKeys[iKeyCode] != null)
return arrKeys[iKeyCode];
return String.fromCharCode(iKeyCode);
}
function GetKeyCode(objEvent) {
if (isIE)
return objEvent.keyCode;
return objEvent.which;
}