在我的 Angularjs 应用程序中,我需要使用以下条件为表单验证的两种模式提供正则表达式。
模式一:
输入框应该接受没有空格的字母数字,它还应该允许用户在字符串的任何地方使用像 ~!@#$-_
这样的字符,除了这些字符不是应允许使用其他字符,例如 (%, &, ^ etc)
。它也不应该允许前导/尾随空格。
例子:
ab@4_w : valid
sd!tye123 : valid
sd%tye123 : Invalid
sd*tye123 : Invalid
$scope.pattern1 = [\w~!@#\$-]+
模式二: 应该只允许字母数字,没有空格,也没有其他字符,包括 (_)。它也不应该允许前导/尾随空格。
例子:
a4hgg5 : Valid
a4_6hy : Invalid
a@yb : invalid
$scope.pattern2 = [\w]+
$scope.pattern1
和 $scope.pattern2
需要修改以满足我上面的要求。
最佳答案
It should not allow leading/trailing whitespace.
在这两种情况下,将 ng-trim="false"
属性添加到 input
元素。
The input box should accept alphanumeric with no space and it should also allow the user to use the characters like
~!@#$-_
any where in the string, except these characters non of the other characters should be allowed like (%
,&
,^
etc).
您的模式是正确的,但不建议转义不必转义的字符,使用:
^[\w~!@#$-]+$
\w
匹配 [a-zA-Z0-9_]
。
注意:如果将模式作为字符串传递,请不要添加 ^
和 $
anchor ,而是加倍反斜杠:"[\\w~ !@#$-]+"
.
Should allow only alphanumeric with no space and no other characters including (
_
).
要简单得多:^[a-zA-Z]+$
。与上述有关 anchor 的评论相同。
关于javascript - Angularjs 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40584328/