<input name="city" ng-pattern="([\w ]+)"
invalid-message="'City is invalid.'"
ng-model="city" type="text"
required-message="'You must enter a city.'" required >
我有一个如上所述的输入字段,我必须只允许单独的字母和空格
,但是上面的输入字段失败了...给我 “City is invalid”
.我尝试了不同的模式组合,但都失败了...... ng-pattern="([a-zA-z ]+)"
最佳答案
您的 ng-pattern
表达式未计算为字符串或正则表达式对象。
如果您想对正则表达式进行硬编码,请将其用引号引起来,以便将其作为字符串求值:
ng-pattern="'[A-Za-z ]+'"
或者,将 ng-pattern
绑定(bind)到一个变量:
ng-pattern="regex"
JS:
$scope.regex = '[A-Za-z ]+';
请注意,^
和 $
是不必要的,因为它们在传递字符串参数时是隐含的:
If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in
^
and$
characters.
关于javascript - 仅允许单词和空格的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39235829/