Javascript ng-pattern 允许单词之间有空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32088402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ng-pattern to allow spaces between words
提问by immirza
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.
How i can tweak this reg to allow space between words as well in addition to letters, numbers, dash and underscore.
例如,如果输入"123 456"
,我会收到我定义的自定义错误。除了字母、数字、破折号和下划线之外,我如何调整这个 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>
回答by immirza
I think I found a very simple and basic solution for my requirement i.e. to allow alphanumeric, _, - and space. Space should be allowed between word and not leading and trailing space.
我想我找到了一个非常简单和基本的解决方案来满足我的要求 i.e. 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.
任何人发现它的问题,请告诉我。
回答by Wiktor Stribi?ew
If you want to allow a space in your input, you need to include it into the character class.
如果要在输入中允许空格,则需要将其包含在字符类中。
According to docs:
根据文档:
ngTrim (optional)
If set tofalse
Angular will not automatically trim the input. This parameter is ignored forinput[type=password]
controls, which will never trim the input.
(default: true)
ngTrim(可选)
如果设置为false
Angular 将不会自动修剪输入。对于input[type=password]
永远不会修剪输入的控件,将忽略此参数。
(默认值:真)
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.
JS中的\w
代表[A-Za-z0-9_]
,下划线不需要转义,字符类末尾的连字符也不需要转义。
回答by vks
^[a-zA-Z0-9_-]+(?:\s+[a-zA-Z0-9_-]+)*$
Construct your regex this way to capture words
and not spaces
at start or end.
以这种方式构建您的正则表达式以捕获words
而不是spaces
在开始或结束时。
回答by Avinash Raj
You may try the below lookaround based regex.
您可以尝试以下基于环视的正则表达式。
^(?!\s)(?=$|.*[a-zA-Z0-9_-]$)[a-zA-Z0-9_\s-]*$
回答by KARTHIKEYAN.A
Use this pattern to solve the issue
使用此模式解决问题
ng-pattern="/^(\D)+$/"
回答by swetha
pls ng-pattern="/^[\w -]*$/"
请 ng-pattern="/^[\w -]*$/"