双/浮点数的jQuery输入验证

时间:2009-10-09 07:43:47

标签: jquery validation input floating-point double

将输入字段屏蔽为仅允许float / double,而不使用任何jquery插件的最佳方法是什么。

我正是这样做的:

$("#defaultvalue").bind("keypress", function(e) {
                if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                    return false;
                }
            });

但仅限于数字 THX

3 个答案:

答案 0 :(得分:1)

当您的输入不是数字时,

JavaScripts parseFloat()函数返回NaN。对于i18n,您可能需要更换浮点分隔符(例如,使用。)

答案 1 :(得分:1)

parseFloat(value) and value.match('^[0-9]*\.[0-9]*$')

我猜你可以放弃parseFloat并只使用正则表达式。

答案 2 :(得分:1)

在HTML页面中只需调用JS SetFloatEntry方法。

示例:

<html>
<script>
$(document).ready(function () {

SetFloatEntry("weight");

});
</script>
<body>
   <input id="weight" type="text" />
</body>
</html>

把它放在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;
}