简体   繁体   English

仅允许单词和空格的正则表达式

[英]regular expression for allowing words and spaces only

<input name="city" ng-pattern="([\w ]+)" 
        invalid-message="'City is invalid.'" 
           ng-model="city" type="text" 
            required-message="'You must enter a city.'" required >

I have an input field as above where i have to allow only alphabets and spaces alone , but the above one fails... throwing me "City is invalid" . 我在上面有一个输入字段,在该输入字段中我只能只允许使用alphabets and spaces alone ,但是上面的输入失败了……丢给我"City is invalid" I tried with different combination of pattern but all fails... ng-pattern="([a-zA-z ]+)" 我尝试使用模式的不同组合,但都失败了…… ng-pattern="([a-zA-z ]+)"

Your ng-pattern expression doesn't evaluate to a string or regular expression object. 您的ng-pattern表达式不会求值到字符串或正则表达式对象。

If you want to hard-code a regular expression, wrap it in quotes so that it's evaluated as a string: 如果要对正则表达式进行硬编码,请将其用引号引起来,以便将其评估为字符串:

ng-pattern="'[A-Za-z ]+'"

Alternatively, bind ng-pattern to a variable: 或者,将ng-pattern绑定到变量:

HTML: HTML:
 ng-pattern="regex" 
JS: JS:
 $scope.regex = '[A-Za-z ]+'; 

Note that the ^ and $ are unnecessary as they are implied when passing a string parameter: 请注意, ^$是不必要的,因为在传递字符串参数时会隐含它们:

If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters. 如果表达式的计算结果为字符串,则将其用^$字符包装后将转换为RegExp。

The following matches any character from az as well as whitespaces, from the beginning to the end of the string: 以下内容从字符串的开头到结尾匹配az和空格中的任何字符:

^[A-Za-z\\s]*$ ^ [A-ZA-Z \\ s] * $

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM