简体   繁体   English

使用正则表达式验证表单(JavaScript正则表达式)

[英]Validating forms with Regular Expressions (Javascript Regex)

I have an input form which needs to be validated in real time (.Keyup and .Load) 我有一个输入表单,需要实时验证(.Keyup和.Load)

It should allow all Az characters (Upper & lower) and the symbols "'", "-" and " " (apostrophe, dash and whitespace). 它应该允许所有Az字符(上和下)以及符号“'”,“-”和“”(撇号,破折号和空白)。

At the moment this is what I have: ([A-Za-z]-\\s\\')* and I'm using it like this: 目前,这就是我所拥有的:([[A-Za-z]-\\ s \\')**,而我正在这样使用它:

var regex = /([A-Za-z]\-\s\')*/;
if (string == "") {
  turn textbox border grey (default)
} else if (!regex.test(string)) {
  turn textbox border red
} else {
  turn textbox border green
}

All it does it change the the textbox green every time (Unless it's blank - it goes grey). 它所做的一切都会使文本框每次都变为绿色(除非它为空白-变为灰色)。 What's the correct expression/technique and what am I doing wrong? 什么是正确的表达/技术,我在做什么错?

You need something like the following: 您需要以下内容:

var regex = /^[A-Za-z\-\s']*$/;

The ^ and $ are beginning and end of string anchors, respectively. ^$分别是字符串锚点的开头和结尾。 Without these the match could start or end anywhere in the string. 没有这些匹配项可能会在字符串中的任何位置开始或结束。 Since * means "repeat the previous element zero or more times" you will match every string no matter the contents because the regex can successfully match zero characters. 由于*表示“将前一个元素重复零次或多次”,因此无论内容如何,​​每个字符串都将匹配,因为正则表达式可以成功匹配零个字符。

The other issue with your current regex is that [A-Za-z]\\-\\s\\' will try to match a letter, a dash, a single whitespace character, and an apostrophe in order (4 characters total). 当前正则表达式的另一个问题是[A-Za-z]\\-\\s\\'将尝试按顺序匹配字母,破折号,单个空格字符和撇号(总共4个字符)。 To match any one of those options you need to put them all inside of the character class (square brackets), or use alternation with the pipe character ( | ) which would look like ([A-Za-z]|-|\\s|') . 要匹配这些选项中的任何一个,您需要将它们全部放在字符类(方括号)内,或与竖线字符( | )交替使用,看起来像([A-Za-z]|-|\\s|') Alternation is more general but character classes are the preferred method for something like this. 交替是更通用的,但是字符类是诸如此类的首选方法。

Regarding the escaping, apostrophe has no special meaning in regular expressions so it does not need to be escaped. 关于转义,撇号在正则表达式中没有特殊含义,因此不需要转义。 A dash only needs to be escaped if it is inside of a character class (if it isn't escaped it is interpreted as part of a range). 如果破折号在字符类中,则仅需将其转义(如果未转义,则将其解释为范围的一部分)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM