仅允许在输入字段中键入数字

时间:2012-09-05 22:03:34

标签: javascript jquery

我希望this website上的电话号码字段只接受数字或数字。我没有编辑HTML代码的权限,所以可以通过定位字段的ID来使用jQuery来完成吗?如果是这样,怎么办呢?

我已经在这个网站上尝试了一些建议,到目前为止还没有任何建议。

提前感谢您的任何帮助!

5 个答案:

答案 0 :(得分:24)

与Jeroen的解决方案类似,这里有一个更清洁,因为它不是替换无效输入,而是完全阻止它。

$('#nbr').on('keypress', function(ev) {
    var keyCode = window.event ? ev.keyCode : ev.which;
    //codes for 0-9
    if (keyCode < 48 || keyCode > 57) {
        //codes for backspace, delete, enter
        if (keyCode != 0 && keyCode != 8 && keyCode != 13 && !ev.ctrlKey) {
            ev.preventDefault();
        }
    }
});

http://jsfiddle.net/PUQGQ/

答案 1 :(得分:13)

使用jQuery挂钩textfield的按键事件。在处理程序中,读取文本字段的值并使用正则表达式替换过滤掉您不想要的所有内容。

更新:未经测试的例子说明:

jQuery("#myPhonefield").keypress(function(){
    var value = jQuery(this).val();
    value = value.replace(/[^0-9]+/g, '');
    jQuery(this).val(value);
});

答案 2 :(得分:5)

您可以按照Jeroen的建议使用jquery的按键;但是,我建议不使用正则表达式。这些方面的东西应该适合你:

$('#test').on('keypress', function(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    return !(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57));
});

Live DEMO

要处理粘贴,您可以对模糊或焦点执行正则表达式检查:

$('#test').on('focusout', function() {
    var value = $(this).val();

    $(this).val(value.replace(/[^0-9]/g, ''));
});

Live Demo

答案 3 :(得分:2)

http://jsfiddle.net/charlescarver/hTMdF/

$("input[type=submit]").click(function() {
    var regex = /\d/g;
    var text = $("input[type=text]").val();
    if (regex(text)) {
        alert("yes");
    }
});​

如果找到号码,这将提醒您。

答案 4 :(得分:2)

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

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']);

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

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

如果指定“自定义”作为验证类型,则必须指定有效字符。 例如:

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