javascript jquery中具有有限特殊字符的正则表达式

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

regular expression with limited special characters in jquery

javascriptjqueryhtmlregexvalidation

提问by patel

I would like to all alphanumeric data + only these following 4 special character are allowed.

我想所有字母数字数据 + 只允许以下 4 个特殊字符。

' (single quote)
- (hyphen)
. (dot)
 single space

I tried this :

我试过这个:

var userinput = $(this).val();
var pattern = [A-Za-z0-9_~\-!@#$%\^&\*\(\)]+$

if(!pattern.test(userinput))
{
  alert('not a valid');
}?

but it is not working.

但它不起作用。

回答by Stefano Sanfilippo

First, you need to enclose the string in /to have it interpreted as a regex:

首先,您需要将字符串括起来/以将其解释为正则表达式:

var pattern = /[A-Za-z0-9_~\-!@#$%\^&\*\(\)]+$/;

Then, you have to remove some unallowed characters (that regex is matching more than you specified):

然后,您必须删除一些不允许的字符(该正则表达式匹配的比您指定的多):

var pattern = /^[A-Za-z0-9 '.-]+$/;

The second one is what you need. Complete code:

第二个是你需要的。完整代码:

var userinput = $(this).val();
var pattern = /^[A-Za-z0-9 '.-]+$/;

if(!pattern.test(userinput))
{
  alert('not a valid');
}?

Besides, check what thispoints to.

此外,检查this指向什么。

回答by npst

"Not working" is not a helpful description of your problem.

“不工作”对您的问题没有帮助。

I'd suggest this regular expresion:

我建议这个正则表达式:

^[a-zA-Z0-9\'\-\. ]+$