javascript 将输入限制为数字和 . 在输入字段上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8936018/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:03:20  来源:igfitidea点击:

Limit input to numbers and . on input field

javascripthtmlforms

提问by 422

Following on from another question I asked, i really didnt seem to be getting anywhere. Due to my ineptitude. I chose the guys answer because , well he answered my question.

继我问的另一个问题之后,我似乎真的一无所获。由于我的无能。我选择了这些人的答案,因为他回答了我的问题。

I am gathering I didnt ask the right question cos I have no idea what to do ..

我正在收集我没有问正确的问题因为我不知道该怎么做..

So issue is I have input element . Keeping it simple;

所以问题是我有输入元素。保持简单;

<input type="text" maxlength="12" name="price" id="price" class="foo">

I want users to be able to type in numbers only and only one period ( . ) anywhere in that price. so could be 3.00 or 300.00 or 3000

我希望用户只能输入数字,并且只能在该价格的任何位置输入一个句点 ( . )。所以可能是 3.00 或 300.00 或 3000

Could someone please help me out, I am going goggle eyed.

谁能帮帮我,我要瞪大眼睛了。

The Older question asked was here Quick regex with alert

较旧的问题是在这里Quick regex with alert

回答by cambraca

You could, in the changeevent of the input, check if the number format is OK. This code will try to get the number and remove anything else: (I'm assuming you use jQuery, if not, please do)

您可以在change输入的情况下检查数字格式是否正确。此代码将尝试获取数字并删除其他任何内容:(我假设您使用 jQuery,如果没有,请执行)

$('#price').change(function() {
    $(this).val($(this).val().match(/\d*\.?\d+/));
});

See it working here.

看到它在这里工作。

EDIT: if you don't have jQuery, this code does the same (at least in Chrome):

编辑:如果您没有 jQuery,则此代码执行相同的操作(至少在 Chrome 中):

document.getElementById('price').onchange = function() {
    this.value = this.value.match(/\d*\.?\d+/);
};

EDIT 2: not sure if I follow, but you could add this too to prevent letters and other characters beforethe changeevent:

编辑 2:不确定我是否遵循,但您也可以添加它以防止事件发生的字母和其他字符change

$('#price').keypress(function(event) {
    var code = (event.keyCode ? event.keyCode : event.which);
    if (!(
            (code >= 48 && code <= 57) //numbers
            || (code == 46) //period
        )
        || (code == 46 && $(this).val().indexOf('.') != -1)
       )
        event.preventDefault();
});

回答by Frans

Here is my solution(It also validates data/values copy&pasted):

这是我的解决方案(它还验证数据/值复制和粘贴):

function InputValidator(input, validationType, validChars) {
if (input === null || input.nodeType !== 1 || input.type !== 'text' && input.type !== 'number')
    throw ('Please specify a valid input');

if (!(InputValidator.ValidationType.hasOwnProperty(validationType) || validationType))
    throw 'Please specify a valid Validation type';

input.InputValidator = this;

input.InputValidator.ValidCodes = [];

input.InputValidator.ValidCodes.Add = function (item) {
    this[this.length] = item;
};

input.InputValidator.ValidCodes.hasValue = function (value, target) {
    var i;
    for (i = 0; i < this.length; i++) {
        if (typeof (target) === 'undefined') {
            if (this[i] === value)
                return true;
        }
        else {
            if (this[i][target] === value)
                return true;
        }
    }

    return false;
};

var commandKeys = {
    'backspace': 8,
    'tab': 9,
    'enter': 13,
    'shift': 16,
    'ctrl': 17,
    'alt': 18,
    'pause/break': 19,
    'caps lock': 20,
    'escape': 27,
    'page up': 33,
    'page down': 34,
    'end': 35,
    'home': 36,
    'left arrow': 37,
    'up arrow': 38,
    'right arrow': 39,
    'down arrow': 40,
    'insert': 45,
    'delete': 46,
    'left window key': 91,
    'right window key': 92,
    'select key': 93,
    /*creates Confusion in IE */
    //'f1': 112,
    //'f2': 113,
    //'f3': 114,
    //'f4': 115,
    //'f5': 116,
    //'f6': 117,
    //'f7': 118,
    //'f8': 119,
    //'f9': 120,
    //'f10': 121,
    //'f11': 122,
    //'f12': 123,
    'num lock': 144,
    'scroll lock': 145,
};

commandKeys.hasValue = function (value) {
    for (var a in this) {
        if (this[a] === value)
            return true;
    }

    return false;
};

function getCharCodes(arrTarget, chars) {
    for (var i = 0; i < chars.length; i++) {
        arrTarget.Add(chars[i].charCodeAt(0));
    }
}

function triggerEvent(name, element) {
    if (document.createEventObject) {
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on' + name, evt)
    }
    else {
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(name, true, true); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

if (validationType == InputValidator.ValidationType.Custom) {
    if (typeof (validChars) === 'undefined')
        throw 'Please add valid characters';

    getCharCodes(input.InputValidator.ValidCodes, validChars);
}
else if (validationType == InputValidator.ValidationType.Decimal) {
    getCharCodes(input.InputValidator.ValidCodes, '0123456789.');
}
else if (validationType == InputValidator.ValidationType.Numeric) {
    getCharCodes(input.InputValidator.ValidCodes, '0123456789');
}

input.InputValidator.ValidateChar = function (c) {
    return this.ValidCodes.hasValue(c.charCodeAt(0));
}

input.InputValidator.ValidateString = function (s) {
    var arr = s.split('');

    for (var i = 0; i < arr.length; i++) {
        if (!this.ValidateChar(arr[i])) {
            arr[i] = '';
        }
    }

    return arr.join('');
}

function bindEvent(el, eventName, eventHandler) {
    if (el.addEventListener) {
        el.addEventListener(eventName, eventHandler, false);
    } else if (el.attachEvent) {
        el.attachEvent('on' + eventName, eventHandler);
    }
}

function getCaretPosition(i) {
    if (!i) return;

    if ('selectionStart' in i) {
        return i.selectionStart;
    }
    else {
        if (document.selection) {
            var sel = document.selection.createRange();
            var selLen = document.selection.createRange().text.length;
            sel.moveStart('character', -i.value.length);
            return sel.text.length - selLen;
        }
    }
}

function setCursor(node, pos) {
    var node = (typeof (node) === "string" || node instanceof String) ? document.getElementById(node) : node;

    if (!node) {
        return false;
    }
    else if (node.createTextRange) {
        var textRange = node.createTextRange();
        textRange.collapse(true);
        textRange.moveEnd(pos);
        textRange.moveStart(pos);
        textRange.select();
        return true;
    } else if (node.setSelectionRange) {
        node.setSelectionRange(pos, pos);
        return true;
    }

    return false;
}

function validateActive() {
    if (input.isActive) {
        var pos = getCaretPosition(input);

        var arr = input.value.split('');

        for (var i = 0; i < arr.length; i++) {
            if (!this.ValidateChar(arr[i])) {
                arr[i] = '';

                if (pos > i)
                    pos--;
            }
        }
        console.log('before : ' + input.value);

        input.value = arr.join('');
        console.log('after : ' + input.value, input);
        setCursor(input, pos);

        setTimeout(validateActive, 10);
    }
}

bindEvent(input, 'keypress', function (e) {
    var evt = e || window.event;
    var charCode = evt.which || evt.keyCode;

    if (!input.InputValidator.ValidCodes.hasValue(charCode) && !commandKeys.hasValue(charCode)) {
        if (evt.preventDefault) {
            evt.preventDefault();
            evt.stopPropagation();
        }
        return false;
    }
});

bindEvent(input, 'keyup', function (e) {
    var evt = e || window.event;
    var charCode = evt.which || evt.keyCode;

    if (!input.InputValidator.ValidCodes.hasValue(charCode) && !commandKeys.hasValue(charCode)) {
        if (evt.preventDefault) {
            evt.preventDefault();
            evt.stopPropagation();
        }
        return false;
    }
});

bindEvent(input, 'change', function (e) {
    var dt = input.value;

    input.value = input.InputValidator.ValidateString(input.value);

    if (input.value !== dt)
        triggerEvent('change', input);
});

bindEvent(input, 'blur', function (e) {
    var dt = input.value;
    input.value = input.InputValidator.ValidateString(input.value);

    input.isActive = false;

    if (input.value !== dt)
        triggerEvent('blur', input);
});

bindEvent(input, 'paste', function (e) {
    var evt = e || window.event;
    var svt = input.value;

    if (evt && evt.clipboardData && evt.clipboardData.getData) {// Webkit - get data from clipboard, put into editdiv, cleanup, then cancel event
        if (/text\/html/.test(evt.clipboardData.types)) {
            var dt = evt.clipboardData.getData('text/html');

            input.value = input.InputValidator.ValidateString(dt);
            if (input.value !== dt)
                triggerEvent('change', input);
        }
        else if (/text\/plain/.test(e.clipboardData.types)) {
            var dt = evt.clipboardData.getData('text/plain');

            input.value = input.InputValidator.ValidateString(dt);
            if (input.value !== dt)
                triggerEvent('change', input);
        }
        else {
            input.value = '';
        }
        waitforpastedata(input, svt);
        if (e.preventDefault) {
            e.stopPropagation();
            e.preventDefault();
        }
        return false;
    }
    else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
        input.value = '';
        waitforpastedata(input, svt);
        return true;
    }
});

bindEvent(input, 'select', function (e) {
    var evt = e || window.event;

    if (evt.preventDefault) {
        evt.preventDefault();
        evt.stopPropagation();
    }
    return false;
});

bindEvent(input, 'selectstart', function (e) {
    var evt = e || window.event;

    if (evt.preventDefault) {
        evt.preventDefault();
        evt.stopPropagation();
    }
    return false;
});

/* no need to validate wile active,
   removing F keys fixed IE compatability*/
//bindEvent(input, 'fucus', function (e) {
//    input.isActive = true;
//    validateActive();
//});

//validate current value of the textbox
{
    var dt = input.value;
    input.value = input.InputValidator.ValidateString(input.value);

    //trigger event to indicate value has changed
    if (input.value !== dt)
        triggerEvent('change', input);
}

function waitforpastedata(elem, savedcontent) {
    if (elem.value !== '') {
        var dt = input.value;
        elem.value = elem.InputValidator.ValidateString(elem.value);

        if (input.value !== dt)
            triggerEvent('change', input);
    }
    else {
        var that = {
            e: elem,
            s: savedcontent
        }
        that.callself = function () {
            waitforpastedata(that.e, that.s)
        }
        setTimeout(that.callself, 10);
    }
}
}

InputValidator.ValidationType = new (function (types) {
    for (var i = 0; i < types.length; i++) {
        this[types[i]] = types[i];
    }
})(['Numeric', 'Custom', 'Decimal']);

To apply it to an input, do the following :

要将其应用于输入,请执行以下操作:

new InputValidator(document.getElementById('txtValidate'), InputValidator.ValidationType.Decimal);/* Numeric or Custom */

If you specify Custom as the validation type you have to specify the valid characters. eg :

如果您指定 Custom 作为验证类型,则必须指定有效字符。例如:

new InputValidator(document.getElementById('txtValidate'), InputValidator.ValidationType.Custom,'1234abc');

回答by Juan Mendes

Cambraca aproach kind of works, but the best one is the last mentioned approach , you cancel the keypress event filtering the keys before it shows up instead of undoing what was already done. A consequence of changing the value after the fact is that it may affect the position of the caret in the field.

Cambraca 方法是可行的,但最好的方法是最后提到的方法,您可以在按键出现之前取消按键事件过滤键,而不是撤消已经完成的操作。事后更改值的结果是它可能会影响插入符号在字段中的位置。

Here's an example of abstracting the idea in a cross-browser way. Somebody should port this to a jQuery plugin http://www.qodo.co.uk/assets/files/javascript-restrict-keyboard-character-input.html

这是一个以跨浏览器的方式抽象思想的例子。有人应该将它移植到 jQuery 插件http://www.qodo.co.uk/assets/files/javascript-restrict-keyboard-character-input.html

Ok, I guess I'll port it. But I'm not a jQuery guy so this is an untestedbare bones jQuery plugin that uses their code http://jsfiddle.net/mendesjuan/VNSU7/3

好的,我想我会移植它。但我不是一个 jQuery 人,所以这是一个未经测试的裸骨 jQuery 插件,它使用他们的代码 http://jsfiddle.net/mendesjuan/VNSU7/3

(function( $ ) {
    $.fn.restrict = function(regExp, additionalRestriction) {
        function restrictCharacters(myfield, e, restrictionType) {
            var code = e.which;
            var character = String.fromCharCode(code);
            // if they pressed esc... remove focus from field...
            if (code==27) { this.blur(); return false; }
            // ignore if they are press other keys
            // strange because code: 39 is the down key AND ' key...
            // and DEL also equals .
            if (!e.originalEvent.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) {
                if (character.match(restrictionType)) {
                    return additionalRestriction(myfield.value, character);
                } else {
                    return false;
                }
            }
        }
        this.keypress(function(e){
            if (!restrictCharacters(this, e, regExp)) {
                e.preventDefault();
            }
        });
    };
})( jQuery );

$('#field').restrict(/[0-9\.]/g, function (currentValue, newChar) {
    return !(currentValue.indexOf('.') != -1 && newChar == ".");    
});