[英]Clientside validation for regex - allowing whitespace in middle but not beginning and end
I'm allowing whitespace for this regex like this: 我允许这个正则表达式的空格像这样:
javascript: JavaScript的:
var re_username = /^[a-zA-Z\040\.\-]+$/;
var is_username = re_username.test($('#chatusername').val());
console.log(is_username);
... but I want to disallow it at the beginning and at the end. ......但我想在开始和结束时不允许它。 This worked:
这有效:
javascript: JavaScript的:
var re_username = /^[a-zA-Z]+[a-zA-Z\040\.\-]+[a-zA-Z\.]+$/;
... but I need to enter at least 3 (<3 digits returns false although I enter eg A) digits for the regex to return true which causes trouble adding classes and stuff ... ...但是我需要输入至少3个(<3位数字返回false,尽管我输入例如A)数字,正则表达式返回true,这会导致添加类和东西的麻烦......
I've found this for this allowing whitespaces at the beginning and end 我发现这个允许开头和结尾的空格
javascript: JavaScript的:
var re_username = /^\S+(?: \S+)*$/
But it's allowing all characters ... . 但它允许所有角色...... How can I match my targeted regex?
我如何匹配我的目标正则表达式? I tried this ... but it already didn't work ..
我试过这个...但它已经无法正常工作..
var re_username = /^\S+([a-zA-Z]\040\S+)*$/;
Use 使用
var re_username = /^[a-zA-Z.-]+(?:\040+[a-zA-Z.-]+)*$/;
It will match 它会匹配
^
- start of string ^
- 字符串的开头 [a-zA-Z.-]+
- 1+ letters, .
[a-zA-Z.-]+
- 1+个字母, .
and -
-
(?:\\040+[a-zA-Z.-]+)*
- 0+ sequences of (?:\\040+[a-zA-Z.-]+)*
- 0+序列
\\040+
- 1+ regular spaces \\040+
- 1 +个常规空间 [a-zA-Z.-]+
- 1+ letters, .
[a-zA-Z.-]+
- 1+个字母, .
and -
-
$
- end of string $
- 结束字符串 See the regex demo . 请参阅正则表达式演示 。
NOTE: if you do not want to allow consecutive multiple spaces, remove the +
after \\040
. 注意:如果您不想允许连续多个空格,请在
\\040
之后删除+
。
Another, less efficient way, is via lookaheads: 另一种效率较低的方法是通过前瞻:
var re_username = /^(?!\040|.*\040$)[a-zA-Z\040.-]+$/;
^^^^^^^^^^^^^^^
Here, the (?!\\040|.*\\040$)
negative lookahead will fail the match if a space is found right at the start of a string or after any 0+ chars ( .*
) at the end of the string ( $
). 如果在字符串的开头找到一个空格,或者在字符串末尾的任何0+字符(
.*
)后找到空格,则(?!\\040|.*\\040$)
否定前瞻将使匹配失败( $
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.