简体   繁体   中英

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" . I tried with different combination of pattern but all fails... ng-pattern="([a-zA-z ]+)"

Your ng-pattern expression doesn't evaluate to a string or regular expression object.

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:

HTML:
 ng-pattern="regex" 
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.

The following matches any character from az as well as whitespaces, from the beginning to the end of the string:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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