Javascript 限制特殊字符的正则表达式

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

Regular Expression to restrict special characters

javascriptregex

提问by hemc4

i have an address field in my form and i want to restrict
* | \ " : < > [ ] { } \ ( ) '' ; @ & $
i have tried with

我的表单中有一个地址字段,我想限制
* | \ " : < > [ ] { } \ ( ) '' ; @ & $
我尝试过的

var nospecial=/^[^* | \ " : < > [ ] { } ` \ ( ) '' ; @ & $]+$/;
            if(address.match(nospecial)){
                alert('Special characters like * | \ " : < > [ ] { } ` \ ( ) \'\' ; @ & $ are not allowed');
                return false;

but it is not working. Please tell me what i missed?

但它不起作用。请告诉我我错过了什么?

回答by Ted Hopp

You need to escape the closing bracket (as well as the backslash) inside your character class. You also don't need all the spaces:

您需要转义字符类中的结束括号(以及反斜杠)。您也不需要所有空格:

var nospecial=/^[^*|\":<>[\]{}`\()';@&$]+$/;

I got rid of all your spaces; if you want to restrict the space character as well, add one space back in.

我摆脱了你所有的空间;如果您还想限制空格字符,请重新添加一个空格。

EDITAs @fab points out in a comment, it would be more efficient to reverse the sense of the regex:

编辑正如@fab 在评论中指出的那样,反转正则表达式的意义会更有效:

var specials=/[*|\":<>[\]{}`\()';@&$]/;

and test for the presence of a special character (rather than the absence of one):

并测试是否存在特殊字符(而不是不存在):

if (specials.test(address)) { /* bad address */ }

回答by Munavar

Use the below function

使用以下功能

function checkSpcialChar(event){
    if(!((event.keyCode >= 65) && (event.keyCode <= 90) || (event.keyCode >= 97) && (event.keyCode <= 122) || (event.keyCode >= 48) && (event.keyCode <= 57))){
        event.returnValue = false;
        return;
    }
    event.returnValue = true;
}