ng-pattern在正则表达式应禁止时允许空间 [英] ng-pattern allows space when regex should prohibit it

查看:136
本文介绍了ng-pattern在正则表达式应禁止时允许空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ng-pattern允许使用以下模式的空格,但我不明白为什么会这样做.

ng-pattern="/^[a-zA-Z\d\-\_]+$/"

我尝试不转义-_,结果是相同的:应用了类ng-validng-valid-pattern.

我试图只允许a-z(大写和小写)以及破折号和下划线.该模式似乎可以按我期望的那样在 regex101 上工作,所以这很令人困惑. >

更新: 在空格后键入有效字符后,文本字段被标记为无效,但在空格为第一个字符时则不会: 例如(不是真正的硬编码,在文本输入中键入"someText"和"some text"):

<input> someText</input> //ng-valid
<input>some text</input> //ng-invalid

还是很困惑为什么会这样.

解决方案

角度自动修剪输入.您可以通过ng-trim ="false"

禁用它

<input type="text" ng-model="model" ng-trim="false" ng-pattern="/^[a-zA-Z\d\-\_]+$/"/>

请参见 https://docs.angularjs.org/api/ng/input/input%5Btext%5D

ng-pattern is allowing spaces with the following pattern and I cannot understand why it would do so.

ng-pattern="/^[a-zA-Z\d\-\_]+$/"

I have tried without escaping the - and _, and the result is the same: the classes ng-valid and ng-valid-pattern are applied.

I am trying to only allow a-z (both capital and lower case) and dash and underscore. The pattern seems to work as I'd expect on regex101 so this is quite confusing.

UPDATE: the text field is marked as invalid after a valid character is typed after a space, but not when the space is the first character: eg (not really hardcoded like this, the "someText" and "some text" are typed into the text inputs):

<input> someText</input> //ng-valid
<input>some text</input> //ng-invalid

Still quite confused why this would be.

解决方案

Angular trims inputs automatically. You can disable it by ng-trim="false"

<input type="text" ng-model="model" ng-trim="false" ng-pattern="/^[a-zA-Z\d\-\_]+$/"/>

see https://docs.angularjs.org/api/ng/input/input%5Btext%5D

这篇关于ng-pattern在正则表达式应禁止时允许空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆