[英]javascript regex to require at least one special character
I've seen plenty of regex examples that will not allow any special characters. 我已经看到很多正则表达式的例子,不允许任何特殊字符。 I need one that requires at least one special character.
我需要一个至少需要一个特殊字符的人。
I'm looking at a C# regex 我正在看一个C#正则表达式
var regexItem = new Regex("^[a-zA-Z0-9 ]*$");
Can this be converted to use with javascript? 可以将其转换为与javascript一起使用吗? Do I need to escape any of the characters?
我是否需要逃避任何角色?
Based an example I have built this so far: 基于一个例子我到目前为止已经构建了这个:
var regex = "^[a-zA-Z0-9 ]*$";
//Must have one special character
if (regex.exec(resetPassword)) {
isValid = false;
$('#vsResetPassword').append('Password must contain at least 1 special character.');
}
Can someone please identify my error, or guide me down a more efficient path? 有人可以识别我的错误,还是引导我走更有效的道路? The error I'm currently getting is that regex has no 'exec' method
我目前得到的错误是正则表达式没有'exec'方法
In javascript, regexs are formatted like this: 在javascript中,正则表达式的格式如下:
/^[a-zA-Z0-9 ]*$/
Note that there are no quotation marks and instead you use forward slashes at the beginning and end. 请注意,没有引号,而是在开头和结尾使用正斜杠。
Your problem is that "^[a-zA-Z0-9 ]*$"
is a string, and you need a regex: 你的问题是
"^[a-zA-Z0-9 ]*$"
是一个字符串,你需要一个正则表达式:
var regex = /^[a-zA-Z0-9 ]*$/; // one way
var regex = new RegExp("^[a-zA-Z0-9 ]*$"); // another way
[ more information ] [ 更多信息 ]
Other than that, your code looks fine. 除此之外,您的代码看起来还不错。
In javascript, you can create a regular expression object two ways. 在javascript中,您可以通过两种方式创建正则表达式对象。
1) You can use the constructor method with the RegExp
object (note the different spelling than what you were using): 1)您可以将构造函数方法与
RegExp
对象一起使用(请注意与您使用的拼写不同的拼写):
var regexItem = new RegExp("^[a-zA-Z0-9 ]*$");
2) You can use the literal syntax built into the language: 2)您可以使用语言中内置的文字语法:
var regexItem = /^[a-zA-Z0-9 ]*$/;
The advantage of the second is that you only have to escape a forward slash, you don't have to worry about quotes. 第二个优点是你只需要逃避正斜杠,你不必担心引号。 The advantage of the first is that you can programmatically construct a string from various parts and then pass it to the RegExp constructor.
第一个优点是您可以通过编程从各个部分构造一个字符串,然后将其传递给RegExp构造函数。
Further, the optional flags for the regular expression are passed like this in the two forms: 此外,正则表达式的可选标志以两种形式像这样传递:
var regexItem = new RegExp("^[A-Z0-9 ]*$", "i");
var regexItem = /^[A-Z0-9 ]*$/i;
In javascript, it seems to be a more common convention to the user /regex/
method that is built into the parser unless you are dynamically constructing a string or the flags. 在javascript中,除非您正在动态构造字符串或标志,否则似乎是解析器中内置的用户
/regex/
方法的更常见约定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.