只允许数字和字母输入字符串

L_O*_*L_O 3 html javascript regex validation input

我试图避免在我的输入字符串中输入除数字和字母以外的任何标记page.php

<input type="text" id="input"> 
Run Code Online (Sandbox Code Playgroud)

从这个答案只允许输入英文字符和数字 <input type="text" id="input" class="clsAlphaNoOnly">

$(document).ready(function () {
  $('.clsAlphaNoOnly').keypress(function (e) {  // Accept only alpha numerics, no special characters 
        var regex = new RegExp("^[a-zA-Z0-9 ]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }

        e.preventDefault();
        return false;
    }); 
})
Run Code Online (Sandbox Code Playgroud)

或这个:

$(function(){
    $("#input").keypress(function(event){
        var ew = event.which;
        if(ew == 32)
            return true;
        if(48 <= ew && ew <= 57)
            return true;
        if(65 <= ew && ew <= 90)
            return true;
        if(97 <= ew && ew <= 122)
            return true;
        return false;
    });
});
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,字符串都是明确的,但我使用两种类型的输入,通过单击按钮 $("#btn").click(function()来处理输入,并$(document).keypress(function(e)通过点击键盘上的 Enter 键进行相同的输入。由于某种原因,如果我包含此方法以避免在字符串中添加额外标记,则按 Enter 键不允许输入插入的值。

这种方式工作正常:

<input type="text" id="input"  onkeypress="return (event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode >= 48 && event.charCode <= 57)" />
Run Code Online (Sandbox Code Playgroud)

但我想避免额外的代码htmlin page.php。我想弄清楚,是什么原因导致使用给定方法阻止输入插入值

Chi*_*fie 5

验证的一种方法是使用元素pattern上的属性input

MDN: https: //developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation#Validating_against_a_regular_expression

在你的情况下:

<input type="text" pattern="[a-zA-Z0-9]*">
Run Code Online (Sandbox Code Playgroud)


Tom*_*Tom 5

会告诉你可能会错过事件参数吗?

在 3 个浏览器中,没有 jQuery 对我来说是这样的:

function clsAlphaNoOnly (e) {  // Accept only alpha numerics, no special characters 
    var regex = new RegExp("^[a-zA-Z0-9 ]+$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (regex.test(str)) {
        return true;
    }

    e.preventDefault();
    return false;
}
function clsAlphaNoOnly2 () {  // Accept only alpha numerics, no special characters 
    return clsAlphaNoOnly (this.event); // window.event
}
Run Code Online (Sandbox Code Playgroud)
<input type="text" id="input" onkeypress="clsAlphaNoOnly(event)" onpaste="return false;">
<input type="text" id="input" onkeypress="clsAlphaNoOnly2()" onpaste="return false;">
Run Code Online (Sandbox Code Playgroud)