javascript jQuery 只允许数字、字母和连字符

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

jQuery only allow numbers,letters and hyphens

javascriptjqueryregex

提问by Frank

How can I remove everything but numbers,letters and hyphens from a string with jQuery?

如何使用 jQuery 从字符串中删除除数字、字母和连字符以外的所有内容?

I found this code which allows only alphanumerical characters only but I'm not sure how I would go about adding a hyphen.

我发现这段代码只允许使用字母数字字符,但我不确定如何添加连字符。

$('#text').keypress(function (e) {
    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;
});

回答by Sylvain

You just have to change the regexp to this : "^[a-zA-Z0-9\-]+$".

您只需要将正则表达式更改为:"^[a-zA-Z0-9\-]+$"

Note that the hyphen is escaped using \, otherwise it is used to specify a range like a-z(characters from ato z).

请注意,连字符使用 转义\,否则用于指定范围,如a-z(字符从az)。

This code will only check if the last typed character is in the allowed list, you might also want to check if after a paste in your field, the value is still correct :

此代码只会检查最后输入的字符是否在允许列表中,您可能还想检查在您的字段中粘贴后,该值是否仍然正确:

// The function you currently have
$('#text').keypress(function (e) {
    var allowedChars = new RegExp("^[a-zA-Z0-9\-]+$");
    var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
    if (allowedChars.test(str)) {
        return true;
    }
    e.preventDefault();
    return false;
}).keyup(function() {
    // the addition, which whill check the value after a keyup (triggered by Ctrl+V)
    // We take the same regex as for allowedChars, but we add ^ after the first bracket : it means "all character BUT these"
    var forbiddenChars = new RegExp("[^a-zA-Z0-9\-]", 'g');
    if (forbiddenChars.test($(this).val())) {
        $(this).val($(this).val().replace(forbiddenChars, ''));
    }
});

回答by Peter Alfvin

Since there is so much attention on including a hyphen within a character class amongst these answers and since I couldn't find this information readily by Googling, I thought I'd add that the hyphen doesn't need to be escaped if it's the first character in the class specification. As a result, the following character class will work as well to specify the hyphen in addition to the other characters:

由于在这些答案中的字符类中包含连字符受到了如此多的关注,并且由于我无法通过谷歌搜索轻松找到这些信息,我想我想补充一点,如果连字符是第一个,则不需要转义类规范中的字符。因此,除了其他字符之外,以下字符类也可以用于指定连字符:

[-a-zA-Z0-9]

回答by C1pher

I think you can just put a hyphen inside the square brackets.

我认为你可以在方括号内放一个连字符。

"^[a-z A-Z 0-9 -]+$"