限制Android设备的字段输入

时间:2019-03-07 20:11:32

标签: javascript jquery html

我有一个名称字段,仅允许用户输入字母字符。 我使用了多种防止无效字符的方法,包括正则表达式和JavaScript事件。这需要同时适用于计算机和移动设备。但是,特别是对于Android设备,似乎存在一个问题(我相信OS会覆盖或不适用于PC的代码)。在所有设备上只允许使用字母字符的最佳方法是什么?

这就是我现在的做法。

HTML

<input runat="server" class="form-control restrictNameInput" id="firstName" name="firstName" maxlength="50" type="text" required />

JS

$("input.restrictNameInput").keypress(restrictNameInput);//prevents on keypress, works on computers.

//This is a catch all that goes back and strips invalid characters:
$("input.restrictNameInput").on('keydown keyup keypress change blur focus focusin focusout paste', function () {
    var stripped = $(this).val().replace(/[^\-\'a-zA-Z ]+/i, '');
    $(this).val(stripped);
});

function restrictNameInput(e) {
    if (!((e.which > 64 && e.which < 91) || (e.which > 96 && e.which < 123) || e.which == 32 || e.which == 39 || e.which == 45)) {
        e.preventDefault();
    }
}

1 个答案:

答案 0 :(得分:1)

一个可能的原因是您没有绑定足够的侦听器来捕获文本框的所有输入法。

.on('keydown keyup keypress change blur focus focusin focusout paste input propertychange', function () {

以我的经验,不同的浏览器对于触发这些事件的逻辑将有所不同。这可能不是最优雅的解决方案,但应该可以。