简体   繁体   中英

how to include qutoes + double quotes in ng-regex?

I have phonegap application developed in android studio.

I have an input field that has to allow abc characters, quotes and double quotes.
wanted html code:

 <input placeholder="last name" type="text" ng-model="currentUser.LastName"
                       ng-pattern='/^([A-Za-z\"\' ]){1,45}$/'
                       required
                       class="form-control"/>

but I have a problem - the quotes in the regex close the whole regex.
what I can do:

ng-pattern='/^([A-Za-z\" ]){1,45}$/'

or

ng-pattern="/^([A-Za-z\' ]){1,45}$/"

but I cant find way to include quotes marks and double quotes, too.

I tried it:

in scope:

$scope.regex=/^([A-Za-z\"\' ]){1,45}$/;

in html page:

<input placeholder="last name" type="text" ng-model="currentUser.LastName" name="userLastName1"
                       ng-pattern='{{regex}}'
                       required
                       class="form-control"/>

it did not work, too (my editor is android studio, maybe other editors are better?).

is there any way to include both quotes and double quotes in one regex?

You can use hex values for those entities, \\x22 for " and \\x27 for ' :

$scope.regex= "/^[A-Za-z\x22\x27 ]{1,45}$/";

And you need no outer parentheses.

You can test it here .

Or here is a snippet showing it works in an ng-pattern attribute:

 function formCtrl($scope){ $scope.onSubmit = function(){ alert("form submitted"); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app ng-controller="formCtrl"> <form name="myForm" ng-submit="onSubmit()"> <input type="text" name="field" ng-model="formCtrl" ng-pattern="/^[A-Za-z\\x22\\x27 ]{1,45}$/" required placeholder="last name"> <span ng-show="myForm.field.$error.pattern">Not valid!</span> <span ng-show="myForm.field.$error.required">This field is required!</span> <input type="submit" value="submit"/> </form> </div> 

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