[英]ng-pattern to allow spaces between words
I am looking for a regular expression
that prevents special characters and only allows letters, numbers, dash (-), underscore (_) an space .我正在寻找一个防止特殊字符的
regular expression
,并且只允许字母、数字、破折号 (-)、下划线 (_) 和空格。
This regex works great but it doesn't allow for spaces between words.这个正则表达式效果很好,但它不允许单词之间有空格。
For example, if enter "123 456"
, i get custom error i defined.例如,如果输入
"123 456"
,我会收到我定义的自定义错误。 How i can tweak this reg to allow space between words as well in addition to letters, numbers, dash and underscore.除了字母、数字、破折号和下划线之外,我如何调整这个 reg 以允许单词之间有空格。
<input type="text" name="serialNumber" data-ng-model="SerialNumber" ng-pattern="/^[a-zA-Z0-9_-]*$/" maxlength="100"/>
<div data-ng-if="Form.serialNumber.$error.pattern" class="error">Please enter valid serial number</div>
I think I found a very simple and basic solution for my requirement ie to allow alphanumeric, _, - and space. Space should be allowed between word and not leading and trailing space.
我想我找到了一个非常简单和基本的解决方案来满足我的要求,
ie to allow alphanumeric, _, - and space. Space should be allowed between word and not leading and trailing space.
ie to allow alphanumeric, _, - and space. Space should be allowed between word and not leading and trailing space.
ng-pattern="/^[a-zA-Z0-9\_\- ]*$/"
Anybody find issue with it , let me know please.任何人发现它的问题,请告诉我。
If you want to allow a space in your input, you need to include it into the character class.如果要在输入中允许空格,则需要将其包含在字符类中。
ngTrim (optional)
ngTrim(可选)
If set tofalse
Angular will not automatically trim the input.如果设置为
false
Angular 将不会自动修剪输入。 This parameter is ignored forinput[type=password]
controls, which will never trim the input.对于
input[type=password]
控件,此参数将被忽略,它永远不会修剪输入。
(default: true)(默认值:真)
So, if your input field is not password field I'd recommend:因此,如果您的输入字段不是密码字段,我建议:
ng-pattern="/^[\w -]*$/"
The \\w
stands for [A-Za-z0-9_]
in JS, the underscore does not have to be escaped and the hyphen at the end of the character class does not need escaping either. \\w
在 JS 中代表[A-Za-z0-9_]
,下划线不需要转义,字符类末尾的连字符也不需要转义。
^[a-zA-Z0-9_-]+(?:\s+[a-zA-Z0-9_-]+)*$
以这种方式构建您的正则表达式以捕获words
而不是开头或结尾的spaces
。
您可以尝试以下基于环视的正则表达式。
^(?!\s)(?=$|.*[a-zA-Z0-9_-]$)[a-zA-Z0-9_\s-]*$
使用此模式解决问题
ng-pattern="/^(\D)+$/"
请 ng-pattern="/^[\\w -]*$/"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.